鴻蒙圖片轉(zhuǎn)PDF

一、學習筆記

HarmonyOS NEXT API 12


二、實例代碼

將 base64 格式的圖片,轉(zhuǎn)為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轉(zhuǎn)換失敗')
      return
    }

    let pixMap = await uriOrPathConvertPixelMap(filePath)
    if (pixMap == undefined) {
      throw new Error('PDF轉(zhuǎn)換失敗')
      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) { // 是否成功創(chuàng)建文檔
      let pdfPage: pdfService.PdfPage = pdfDocument.getPage(0);
      // pxConvertInch() 像素轉(zhuǎn)英寸;
      let imageWidthIn = WindowUtils.pxConvertInch(imageInfo.size.width) * 72
      let imageHeightIn = WindowUtils.pxConvertInch(imageInfo.size.height) * 72
      // 寬度拉滿時,縮放的倍數(shù)
      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 創(chuàng)建失敗')
      return
    }
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容