Skip to content
DemoAPI 参考文档FAQ

PDF 生成模板编辑器

开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。

查看 GitHub
React Native Guides Redact pdfs

创建与应用标记密文 ​

以下示例使用已完成文档加载的阅读器。应用密文标记会永久移除覆盖区域内的内容,操作不可撤销,请先保留源文件副本。

创建标记 ​

ts
import { CPDFReaderView, CPDFRedactAnnotation, CPDFAlignment }
  from '@compdfkit_pdf_sdk/react_native';

async function addRedaction(reader: CPDFReaderView) {
  await reader._pdfDocument.addAnnotations([
    new CPDFRedactAnnotation({
      page: 0,
      rect: { left: 60, top: 520, right: 320, bottom: 470 },
      overlayText: 'REDACTED', fillColor: '#000000',
      outlineColor: '#FF0000', alignment: CPDFAlignment.CENTER,
      textAttribute: { color: '#FFFFFF', familyName: 'Helvetica',
        styleName: '', fontSize: 14 },
    }),
  ]);
}

page 从 0 开始。rect 使用 PDF 页面坐标,原点在左下角,top 大于 bottom。outlineColor 设置应用前的边框;fillColor、overlayText、textAttribute 和 alignment 设置应用后的覆盖外观。

此时原内容仍存在。可通过 pageAtIndex().getAnnotations() 获取标记,再调用 updateAnnotation() 或 removeAnnotation() 调整或删除标记。

应用单个标记 ​

ts
import { CPDFReaderView, CPDFRedactAnnotation }
  from '@compdfkit_pdf_sdk/react_native';

async function applyFirstRedaction(reader: CPDFReaderView) {
  const document = reader._pdfDocument;
  const annotations = await document.pageAtIndex(0).getAnnotations();
  const redaction = annotations.find(
    (item): item is CPDFRedactAnnotation => item instanceof CPDFRedactAnnotation,
  );
  if (!redaction) return;
  if (!await document.applyRedaction(redaction)) {
    throw new Error('未应用密文标记');
  }
  if (!await reader.save()) throw new Error('保存文档失败');
}

传入对象必须来自当前文档,带有有效的 page 和原生 uuid。不能将尚未添加到文档的 TypeScript 对象直接传给应用接口。

应用全部标记 ​

ts
import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';

async function applyAllRedactions(reader: CPDFReaderView) {
  const applied = await reader._pdfDocument.applyRedactions();
  if (!applied) return false;
  if (!await reader.save()) throw new Error('保存文档失败');
  return true;
}

Android 和 iOS 均提供应用接口。applyRedactions() 返回 true 表示至少应用了一个标记;没有可应用的标记时返回 false。应用应区分未应用与成功,并捕获 Promise 拒绝。