一鼓寺、學(xué)習(xí)筆記
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
}
}