使用PDF Kit创建一个pdf,并插入空白页,在空白页上添加文本和图片,保存。插入空白页和保存都成功了,但文本和图片并没有添加到页面上。显示的是两个空白页。另:save中的进度回调中的log没有输出。具体代码如下:
import { pdfService } from "@kit.PDFKit";
saveAsPdf(savePath: string, images: string[], callback?: Function) {
const tempFilePath: string = `${this.context.tempDir}/${this.dirName}.pdf`;
const pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();
pdfDocument.createDocument(595, 842);
pdfDocument.insertBlankPage(1, 595, 842);
const page = pdfDocument.getPage(1);
page.addTextObject('Hello world', 20, 20, {textColor: Color.Red, textSize: 20});
LogUtil.info('图片:', JSON.stringify(images));
LogUtil.info('沙箱地址:', FileUtil.getFilePath(images[0]));
page.addImageObject(images[0], 0, 0, 595, 842);
pdfDocument.saveDocument(tempFilePath, (progress: number) => {
LogUtil.info('进度:', progress.toString());
return progress;
})
// const loadResult: pdfService.ParseResult = pdfDocument.loadDocument(tempFilePath, '');
// LogUtil.info('加载结果:', loadResult.toString())
// if (pdfService.ParseResult.PARSE_SUCCESS === loadResult) {
// images.forEach((img: string, index: number) => {
// // const pdfPage: pdfService.PdfPage = pdfDocument.getPage(index);
// const pdfPage: pdfService.PdfPage = pdfDocument.insertBlankPage(index, 595, 842);
// const path = FileUtil.getFilePath(img);
// pdfPage.addImageObject(path, 0, 0, 595, 842);
// });
// pdfDocument.saveDocument(savePath, (progress: number) => {
// LogUtil.info('生成进度:', progress.toString());
// if (callback) {
// callback(progress);
// }
// return progress;
// });
// } else {
// LogUtil.error('加载临时PDF失败!')
// }
}
本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。
参考代码: