HarmonyOS 鸿蒙Next中pdf文档添加水印

HarmonyOS 鸿蒙Next中如何在pdf文档预览界面添加水印?

3 回复

开发者你好,PDF添加水印可以参考以下代码实现,请参考:

【背景知识】

PDF Kit(PDF服务)包含pdfService和PdfView组件。其中PdfView组件提供了文档预览功能,如:PDF文档预览、高亮显示、搜索关键字,批注等场景。

【解决方案】

import { pdfService, pdfViewManager, PdfView } from '@kit.PDFKit'
import { common } from '@kit.AbilityKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { font } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  private controller: pdfViewManager.PdfController = new pdfViewManager.PdfController();
  private loadResult: pdfService.ParseResult = pdfService.ParseResult.PARSE_ERROR_FORMAT;

  aboutToAppear(): void {
    let context = getContext() as common.UIAbilityContext;
    let dir: string = context.filesDir
    // 确保在工程目录src/main/resources/rawfile里存在input.pdf文档
    let filePath: string = dir + '/input.pdf';
    let res = fs.accessSync(filePath);
    if (!res) {
      let content: Uint8Array = context.resourceManager.getRawFileContentSync('rawfile/input.pdf');
      let fdSand =
        fs.openSync(filePath, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
      fs.writeSync(fdSand.fd, content.buffer);
      fs.closeSync(fdSand.fd);
    }
    (async () => {
      let loadResult: pdfService.ParseResult = await this.controller.loadDocument(filePath);
      if (pdfService.ParseResult.PARSE_SUCCESS === loadResult) {
        // 添加高亮批注
        this.controller.enableAnnotation(pdfViewManager.SupportedAnnotationType.HIGHLIGHT, 0xFF0000);

        // 监听批注改变后保存文件
        this.controller.registerAnnotationChangedListener(async (annotationChange: pdfViewManager.AnnotationChangedParam) => {
          console.log("annotationChange: ", JSON.stringify(annotationChange));
          let result = await this.controller.saveDocument(filePath);
          console.log('批注保存情况', result)
        });
      }
    })()

  }

  build() {
    Column() {
      Row() {
        // Pdf预览
        PdfView({
          controller: this.controller,
          pageFit: pdfService.PageFit.FIT_WIDTH,
          showScroll: true
        })
          .id('pdfview_app_view')
          .layoutWeight(1);
        Button("添加水印").onClick(async ()=>{
          // 将测试文件上传至应用沙箱路径
          let context = getContext() as common.UIAbilityContext;
          let dir = context.filesDir;
          let tempDir = context.tempDir;
          // 确保该路径下的源文档有读写的权限
          let filePath = dir + `/input.pdf`;
          let tempFilePath = tempDir + `/temp${Math.random()}.pdf`;
          fs.copyFileSync(filePath, tempFilePath);
          let pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();
          // 加载临时文件
          let loadResult = pdfDocument.loadDocument(tempFilePath, '');
          // 对文档加一些水印
          if (pdfService.ParseResult.PARSE_SUCCESS === loadResult) {
            let wminfo: pdfService.TextWatermarkInfo = new pdfService.TextWatermarkInfo();
            wminfo.watermarkType = pdfService.WatermarkType.WATERMARK_TEXT;
            wminfo.content = "This is Watermark";
            wminfo.textSize = 30;
            wminfo.textColor = 200;
            wminfo.fontInfo = new pdfService.FontInfo();
            wminfo.fontInfo.fontPath = font.getFontByName("HarmonyOS Sans").path;
            wminfo.opacity = 0.5;
            wminfo.isOnTop = true;
            wminfo.rotation = 45;
            wminfo.scale = 1.5;
            wminfo.opacity = 0.5;
            wminfo.verticalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_TOP;
            wminfo.horizontalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_LEFT;
            wminfo.horizontalSpace = 1.0;
            wminfo.verticalSpace = 1.0;
            pdfDocument.addWatermark(wminfo, 0, 1, true, true);
            // 保存文件将覆盖源文档
            let result = pdfDocument.saveDocument(filePath);
            console.log('保存情况', result)
          }
        })
      }
      .height('10%')
      PdfView({
        controller: this.controller,
        pageFit: pdfService.PageFit.FIT_WIDTH,
        showScroll: true
      })
        .height('90%')
        .id('pdfview_app_view')
        .layoutWeight(1);
    }
    .width('100%')
    .height('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next中pdf文档添加水印的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可通过@ohos.file.fs@ohos.multimedia.image模块实现PDF水印添加。使用fs模块读取PDF文件,通过image组件创建水印图像或文字,利用Canvas绘制水印内容。调用图像处理接口将水印与PDF页面合成,最后通过fs模块输出带水印的PDF文件。整个过程基于ArkTS语言开发,使用鸿蒙原生API操作文件与图像数据。

在HarmonyOS Next中,可以通过PDFDocumentPDFPage类操作PDF文档。添加水印的步骤如下:

  1. 使用PDFDocument.load()加载PDF文件
  2. 遍历文档页面,对每个页面执行:
    • 创建Canvas对象
    • 使用drawText()方法绘制水印文字
    • 设置透明度、旋转角度等样式
    • 将Canvas内容转换为图片
    • 使用addImage()将水印图片添加到页面

示例代码片段:

let pdfDocument = await PDFDocument.load(pdfData);
for (let i = 0; i < pdfDocument.pageCount; i++) {
  let page = pdfDocument.getPage(i);
  let canvas = new Canvas();
  // 设置水印绘制参数
  canvas.drawText("机密文件", x, y, paint);
  let watermark = canvas.toPixelMap();
  page.addImage(watermark, rect);
}

注意需要处理页面坐标系变换,确保水印位置正确。建议将水印绘制逻辑封装为独立模块便于复用。

回到顶部