PDF无法编辑的问题?

使用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 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

阅读 682
avatarAI BotBETA
### 回答

问题出现在对 PDFKit 的使用上。根据你提供的代码,可能的问题和解决方案如下:

1. **文本和图片未正确添加到页面**:
   - 在 PDFKit 中,文本和图片对象需要添加到页面的内容流中,并且需要在页面内容上下文中进行。你的代码看起来是在尝试添加文本和图片,但可能存在上下文管理的问题。
   - 确保在添加文本和图片之前,页面内容已经开始(例如,通过调用 `page.beginContent()`),并在添加完成后结束内容(`page.endContent()`)。不过,PDFKit 的某些封装可能自动管理这些,具体取决于你使用的 PDFKit 版本和封装。

2. **进度回调未输出**:
   - 进度回调未输出可能是因为 `saveDocument` 方法中的回调没有被正确触发,或者触发时日志系统未能正确记录。
   - 检查 `LogUtil.info` 方法是否能在其他地方正常工作,确保日志系统没有问题。
   - 确认 `saveDocument` 方法是否支持进度回调,以及回调是否在所有情况下都会被触发(例如,在某些错误或异常情况下可能不会触发)。

3. **代码优化和错误处理**:
   - 你的代码中包含了一些被注释掉的部分,这些部分看起来像是用于处理图片加载和页面插入的逻辑。如果这部分逻辑是必要的,确保在正确的地方解注释并测试。
   - 添加错误处理逻辑,以便在出现问题时能够捕获并记录错误。

4. **检查 PDFKit 文档和示例**:
   - 查阅 PDFKit 的官方文档或示例代码,确保你的使用方法是正确的。
   - 特别注意任何关于页面内容管理、对象添加和保存文档的特定要求或限制。

5. **更新和测试**:
   - 确保你使用的 PDFKit 版本是最新的,或者至少是一个已知稳定的版本。
   - 在不同的环境或设备上测试代码,以排除特定环境的问题。

### 建议的修改

由于我无法直接运行你的代码来验证问题,以下是一个基于你提供的代码的修改建议:

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);
const page = pdfDocument.insertBlankPage(1, 595, 842);

// 确保页面内容开始
page.beginContent();
page.drawText('Hello world', {
    x: 20,
    y: 20,
    color: pdfService.Color.red,
    size: 20
});

// 假设 images[0] 是一个有效的图片路径,并且 PDFKit 支持的图片格式
const imgPath = FileUtil.getFilePath(images[0]);
page.drawImage(imgPath, {
    x: 0,
    y: 0,
    width: 595,
    height: 842
});

// 结束页面内容
page.endContent();

pdfDocument.saveDocument(tempFilePath, (progress: number) => {
    LogUtil.info('进度:', progress.toString());
    if (callback) {
        callback(progress);
    }
});

}


**注意**:上述代码中的 `drawText` 和 `drawImage` 方法是假设的,因为具体的 API 调用可能取决于你使用的 PDFKit 版本和封装。你需要根据实际的 PDFKit 文档来调整这些方法。同时,确保 `FileUtil.getFilePath` 方法能够正确返回图片的路径,并且该路径是 PDFKit 可以访问的。
1 个回答

参考代码:

import { fileIo as fs } from '@kit.CoreFileKit';
import { pdfService } from '@kit.PDFKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Page {
  build() {
    Column() {
      Button('转图片')
        .onClick(()=>{
          this.copyFile('index.png')
          this.savePdf()
        })
        .margin(20)

    }
  }

  copyFile(fileName:string){
    let context = getContext(this) as common.UIAbilityContext;
    try {
      let data = context.resourceManager.getRawFileContentSync(fileName)
      let buffer = data.buffer
      let sanboxPath = context.filesDir
      try {
        let filePath = sanboxPath + "/" + fileName
        let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
        try {
          fs.writeSync(file.fd, buffer) // 拷贝文件到沙箱
          fs.close(file.fd)
          console.log('myRawfileCopy success ' + data)
        } catch (err) {
          console.log('myRawfileCopy error')
        }
      } catch (error) {
        let err: BusinessError = error as BusinessError;
        console.error(err.message);
      }
    }catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(err.message);
    }
  }

  savePdf(){
    let filePath = getContext().filesDir + '/pdf002.pdf'
    let imgPath = getContext().filesDir + "/index.png";
    if (!fs.accessSync(filePath)) {
      // 新建并打开文件
      let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      // 关闭文件
      fs.closeSync(file);
    }
    if (!fs.accessSync(imgPath)) {
      console.info("没有图片")
      return
    }
    let tempFilePath = getContext().tempDir + /temp${Math.random()}.pdf;
    fs.copyFileSync(filePath,tempFilePath)
    let pdfDocument = new pdfService.PdfDocument();
    let loadResult = pdfDocument.loadDocument(tempFilePath,'');
    console.info("pdfService.ParseResult.PARSE_SUCCESS:",pdfService.ParseResult.PARSE_SUCCESS)
    pdfDocument.createDocument(728.27,1000)
    let pdfPage: pdfService.PdfPage = pdfDocument.getPage(0);

    pdfPage.addImageObject(imgPath, 0, 0, 728.27, 1000);
    pdfDocument.saveDocument(filePath);
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进