Skip to content
DemoFAQ

PDF 生成模板编辑器

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

查看 GitHub
Flutter Guides Redact pdfs

创建与应用标记密文 ​

ComPDF Flutter SDK 自 3.2.0 起提供 CPDFRedactAnnotation,用于标记需要移除的内容。创建标记仅添加注释;应用标记后,覆盖区域中的内容才会被永久移除。

以下示例中的 document 为已打开的 CPDFDocument。本页应用标记的示例适用于 Android。

dart
import 'package:compdfkit_flutter/annotation/cpdf_redact_annotation.dart';
import 'package:compdfkit_flutter/util/cpdf_rectf.dart';
import 'package:flutter/material.dart';

创建标记 ​

dart
await document.addAnnotations([
  CPDFRedactAnnotation(
    page: 0,
    rect: const CPDFRectF(left: 72, top: 220, right: 300, bottom: 180),
    overlayText: 'Redacted',
    fillColor: Colors.black,
    outlineColor: Colors.red,
  ),
]);

page 从 0 开始,rect 使用 PDF 页面坐标,原点位于页面左下角。通过 overlayText、fillColor、outlineColor、textAttribute 和 alignment 配置标记外观。

读取、修改与删除 ​

创建后重新读取注释,获取具有原生 uuid 的对象。后续操作应使用读取到的对象。

dart
final annotations = await document.pageAtIndex(0).getAnnotations();
final redactions = annotations.whereType<CPDFRedactAnnotation>().toList();
if (redactions.isNotEmpty) {
  final redaction = redactions.first;
  redaction.overlayText = 'Confidential';
  await document.updateAnnotation(redaction);
}

应用前可以通过 document.removeAnnotation(redaction) 删除标记;删除标记不会删除原始内容。

应用单个标记 ​

dart
if (redactions.isNotEmpty) {
  await document.applyRedaction(redactions.first);
  await document.save();
}

应用成功后,该标记注释被移除,原对象不能继续用于修改或应用。请重新读取页面注释。

应用全部标记 ​

dart
await document.applyRedactions();
await document.save();

应用标记会永久移除覆盖区域中的内容,不能通过删除注释恢复。处理前应保留原文件副本。仅保存未应用的标记,不能达到移除敏感内容的目的。