鸿蒙开发入门

鸿蒙图片转PDF

2024-08-15  本文已影响0人  孤街酒客0911

一、学习笔记

HarmonyOS NEXT API 12


二、实例代码

将 base64 格式的图片,转为PDF

  /**
   * @param mOutputPdfFileName 保存的路径;例如:getContext().cacheDir +"/"+fileName
   * @param base64Str  base64格式的图片
   */
  async picConvertPDF(mOutputPdfFileName: string, base64Str: string) {

    let filePath = await base64ImgConvertFilePath(getContext(), base64Str)
    if (filePath == undefined) {
      throw new Error('PDF转换失败')
      return
    }

    let pixMap = await uriOrPathConvertPixelMap(filePath)
    if (pixMap == undefined) {
      throw new Error('PDF转换失败')
      return
    }
    let imageInfo = await pixMap.getImageInfo()
    let pdfDocument = new pdfService.PdfDocument()
    // 一英寸等于72Points,A4纸的尺寸描述为210 x 297毫米 (8.27 x 11.69英寸)
    let documentWidth = 72 * 8.27
    let documentHeigh = 72 * 11.6
    let createResult = pdfDocument.createDocument(documentWidth, documentHeigh)
    if (createResult) { // 是否成功创建文档
      let pdfPage: pdfService.PdfPage = pdfDocument.getPage(0);
      // pxConvertInch() 像素转英寸;
      let imageWidthIn = WindowUtils.pxConvertInch(imageInfo.size.width) * 72
      let imageHeightIn = WindowUtils.pxConvertInch(imageInfo.size.height) * 72
      // 宽度拉满时,缩放的倍数
      let ratio = documentWidth / imageWidthIn

      pdfPage.addImageObject(
        filePath,
        (documentWidth - imageWidthIn * ratio ) / 2,   // 为了图片居中
        (documentHeigh - imageHeightIn * ratio) / 2,  // 为了图片居中
        imageWidthIn * ratio, 
        imageHeightIn * ratio
      )
      pdfDocument.saveDocument(mOutputPdfFileName)
    } else {
      throw new Error('PDF 创建失败')
      return
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读