如何在 .NET 中向 PDF 添加注释和表单

如何在 .NET 中向 PDF 添加注释和表单

如何在 .NET 中添加注释和表单

本指南展示了如何使用 Aspose.PDF FOSS for .NET 向 PDF 文档添加批注和交互式表单字段。


先决条件

RequirementDetail
Runtime.NET 8.0 或更高版本
Packagedotnet add package Aspose.Pdf.Foss
LicenseMIT — 不需要许可证密钥

步骤 1:添加文本批注

文本批注显示为页面上的便利贴。提供一个边界矩形, 批注内容和作者标题。将 open: true 设置为在文档打开时展开显示批注 。

using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
var page = doc.Pages[1];

page.Annotations.AddTextAnnotation(
    new Rectangle(72, 720, 200, 740),
    contents: "Review this section",
    title: "Editor",
    open: true);

doc.Save("annotated.pdf");

步骤 2:添加链接注释

链接注释会使矩形区域可点击。将 Rectangle 与一个
PdfAction.CreateUri 调用结合起来,以在点击时将用户导航到外部 URL。

var action = PdfAction.CreateUri("https://aspose.com");
page.Annotations.AddLinkAnnotation(
    new Rectangle(50, 700, 200, 720), action);

步骤 3:添加高亮和形状批注

高亮注释使用半透明覆盖标记文本区域。 形状
注释(如方形和圆形)在页面上绘制几何轮廓。 两者都接受颜色数组和可选的线宽参数。

page.Annotations.AddHighlightAnnotation(
    new Rectangle(72, 680, 300, 700),
    quadPoints: null,
    color: new double[] { 1, 1, 0 });

page.Annotations.AddSquareAnnotation(
    new Rectangle(72, 640, 200, 680),
    borderColor: new double[] { 0, 0, 1 },
    fillColor: null,
    lineWidth: 1.5);

步骤 4:读取表单字段值

AcroForm 字段通过 Document.Form 访问。遍历 Form.Fields
读取每个字段的名称和当前值,而不修改文档。

using var doc = Document.Open(pdfBytes);
foreach (var field in doc.Form.Fields)
{
    Console.WriteLine($"{field.FullName}: {field.Value}");
}

步骤 5:展平注释

foreach (var annot in doc.Pages[1].Annotations)
{
    annot.Flatten();
}
doc.Save("flattened.pdf");

关键类

目的
AnnotationCollection添加和管理页面注释
LinkAnnotation超链接注释
TextAnnotation便签注释
FormAcroForm 字段访问
Field表单字段的基类
PdfAction.CreateUri创建 URI 链接操作
AnnotationSelector按类型过滤注释

故障排除

ProblemSolution
注释不可见检查矩形坐标是否在页面范围内
链接 URI 为 null链接可能使用 GoTo 动作 — 检查 ActionType
表单字段值为空该字段可能没有 /V 条目 — 验证字段名称

另见

 中文