开发中,PDF处理是一个常见需求。PDF Kit(PDF服务)包含pdfService和PdfView组件,提供PDF文档的加载、编辑、预览等能力。

一、PDF Kit

PDF Kit包含两大模块:

模块 说明
pdfService 加载/保存PDF文档、添加文本/图片/批注/页眉页脚/水印/背景/书签、加密判断/删除加密等
PdfView组件 文档预览、高亮显示、搜索关键字、批注等

二、pdfService与PdfView能力对比

PDF Kit能力 pdfService PdfView预览组件
打开和保存文档 支持 支持
释放文档 支持 支持
PDF文档转图片 支持 支持
添加、删除批注 支持 支持
管理书签 支持 不支持
添加、编辑、删除PDF页 支持 不支持
添加、删除文本内容 支持 不支持
添加、删除图片内容 支持 不支持
编辑页眉页脚、水印、背景 支持 不支持
判断PDF文档是否加密 支持 不支持
删除文档加密 支持 不支持
PDF文档预览 不支持 支持
搜索关键字 不支持 支持
PDF文档监听回调 不支持 支持

三、限制

限制项 说明
支持地区 仅中国境内(港澳台除外)
支持设备 Phone、Tablet、PC/2in1
模拟器 支持ARM模拟器,不支持x86模拟器

四、pdfService核心功能

4.1 添加文本和图片

导入模块
import { pdfService } from '@kit.PDFKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { Font } from '@kit.ArkUI';
示例
@Entry
@Component
struct PdfPage {
  private pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();
  private context = this.getUIContext().getHostContext() as Context;

  aboutToAppear(): void {
    // 确保resfile目录有input.pdf文档
    let filePath = this.context.resourceDir + '/input.pdf';
    this.pdfDocument.loadDocument(filePath);
  }

  build() {
    Column() {
      // 添加文本
      Button('addText').onClick(async () => {
        let page: pdfService.PdfPage = this.pdfDocument.getPage(0);
        let str = 'This is add text object!';
        let fontInfo = new pdfService.FontInfo();
        let font: Font = new Font();
        fontInfo.fontPath = font.getFontByName('HarmonyOS Sans')?.path;
        fontInfo.fontName = '';
        let style: pdfService.TextStyle = { 
          textColor: 0x000000, 
          textSize: 30, 
          fontInfo: fontInfo 
        };
        page.addTextObject(str, 10, 10, style);
        
        let outPdfPath = this.context.filesDir + '/testAddText.pdf';
        let result = this.pdfDocument.saveDocument(outPdfPath);
        hilog.info(0x0000, 'PdfPage', 'addText %{public}s!', result ? 'success' : 'fail');
      })

      // 删除文本
      Button('delText').onClick(async () => {
        let page: pdfService.PdfPage = this.pdfDocument.getPage(0);
        let graphicsObjects = page.getGraphicsObjects();
        let index = graphicsObjects.findIndex(item => item.type === pdfService.GraphicsObjectType.OBJECT_TEXT);
        if (index > -1) {
          page.deleteGraphicsObject(graphicsObjects[index]);
        }
        let outPdfPath = this.context.filesDir + '/testDelText.pdf';
        let result = this.pdfDocument.saveDocument(outPdfPath);
        hilog.info(0x0000, 'PdfPage', 'delText %{public}s!', result ? 'success' : 'fail');
      })

      // 添加图片
      Button('addImage').onClick(async () => {
        let page: pdfService.PdfPage = this.pdfDocument.getPage(0);
        let imagePath = this.context.resourceDir + '/img.jpg';
        page.addImageObject(imagePath, 100, 100, 100, 120);
        let outPdfPath = this.context.filesDir + '/testAddImage.pdf';
        let result = this.pdfDocument.saveDocument(outPdfPath);
        hilog.info(0x0000, 'PdfPage', 'addImage %{public}s!', result ? 'success' : 'fail');
      })
    }
  }
}

4.2 添加文本批注

支持的批注类型共13种,包括:文本批注、下划线批注、高亮批注、删除线批注等。

示例
import { pdfService } from '@kit.PDFKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct PdfPage {
  private pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();
  private context = this.getUIContext().getHostContext() as Context;

  build() {
    Column() {
      // 添加批注
      Button('addTextAnnotation').onClick(async () => {
        let filePath = this.context.filesDir + '/input.pdf';
        this.pdfDocument.loadDocument(filePath);
        
        let page: pdfService.PdfPage = this.pdfDocument.getPage(0);
        let aInfo = new pdfService.TextAnnotationInfo();
        aInfo.iconName = 'Document';
        aInfo.content = 'this is a content';
        aInfo.subject = 'Annotation';
        aInfo.title = 'this is a title';
        aInfo.state = pdfService.TextAnnotationState.MARKED;
        aInfo.x = 200;
        aInfo.y = 200;
        aInfo.color = 0xf9b1b1;
        aInfo.flag = pdfService.AnnotationFlag.PRINTED;
        
        let annotation: pdfService.PdfAnnotation = page.addAnnotation(aInfo);
        let outPdfPath = this.context.filesDir + '/testAddTextAnnotation.pdf';
        let result = this.pdfDocument.saveDocument(outPdfPath);
        this.pdfDocument.releaseDocument();
        hilog.info(0x0000, 'PdfPage', 'addTextAnnotation %{public}s!', result ? 'success' : 'fail');
      })

      // 修改批注
      Button('setAnnotation').onClick(async () => {
        let filePath = this.context.filesDir + '/testAddTextAnnotation.pdf';
        let result = this.pdfDocument.loadDocument(filePath);
        if (result === pdfService.ParseResult.PARSE_SUCCESS) {
          let page: pdfService.PdfPage = this.pdfDocument.getPage(0);
          let annotations = page.getAnnotations();
          if (annotations.length > 0 && annotations[0].type === pdfService.AnnotationType.TEXT) {
            let newAnno = annotations[0];
            page.removeAnnotation(newAnno);
            let annotation = page.addAnnotation(newAnno);
            
            let newInfo = new pdfService.TextAnnotationInfo();
            newInfo.title = "new Title";
            newInfo.content = "new Info";
            newInfo.state = pdfService.TextAnnotationState.MARKED;
            newInfo.x = 100;
            newInfo.y = 100;
            page.setAnnotation(annotation, newInfo);
            
            let outPdfPath = this.context.filesDir + '/testSetAnnotation.pdf';
            let result = this.pdfDocument.saveDocument(outPdfPath);
            this.pdfDocument.releaseDocument();
            hilog.info(0x0000, 'PdfPage', 'setAnnotation %{public}s!', result ? 'success' : 'fail');
          }
        }
      })

      // 删除批注
      Button('removeAnnotation').onClick(async () => {
        let filePath = this.context.filesDir + '/testAddTextAnnotation.pdf';
        let result = this.pdfDocument.loadDocument(filePath);
        if (result === pdfService.ParseResult.PARSE_SUCCESS) {
          let page: pdfService.PdfPage = this.pdfDocument.getPage(0);
          let annotations = page.getAnnotations();
          if (annotations.length > 0 && annotations[0].type === pdfService.AnnotationType.TEXT) {
            page.removeAnnotation(annotations[0]);
            let outPdfPath = this.context.filesDir + '/testRemoveAnnotation.pdf';
            let result = this.pdfDocument.saveDocument(outPdfPath);
            this.pdfDocument.releaseDocument();
            hilog.info(0x0000, 'PdfPage', 'removeAnnotation %{public}s!', result ? 'success' : 'fail');
          }
        }
      })
    }
  }
}

五、核心接口

5.1 文本/图片操作

接口 描述
addTextObject(text, x, y, style) 添加文本内容,只可按行添加
addImageObject(path, x, y, width, height) 在PDF文档的页面中添加图片
deleteGraphicsObject(object) 删除指定的GraphicsObject

5.2 批注操作

接口 描述
addAnnotation(annotationInfo) 在当前页添加批注
setAnnotation(annotation, annotationInfo) 修改批注
removeAnnotation(annotation) 删除批注
getAnnotations() 获取页面所有批注

5.3 文档操作

接口 描述
loadDocument(filePath) 加载PDF文档
saveDocument(outPdfPath) 保存PDF文档
releaseDocument() 释放文档
getPage(index) 获取指定页

六、选择建议

需求 推荐
编辑PDF内容(文本/图片/批注) pdfService
管理书签、页眉页脚、水印 pdfService
加密判断/删除加密 pdfService
PDF文档预览 PdfView组件
搜索关键字 PdfView组件

   鸿蒙PDF Kit包含pdfService(支持文本/图片/批注编辑、书签、页眉页脚、水印、加密处理)和PdfView(支持预览、搜索、高亮),两者能力互补,可以让应用实现专业的PDF文档处理能力。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐