使用 C# 编辑 PDF

PDF 文档的敏感编辑信息。使用 Aspose.PDF for .NET 以编程方式修改 PDF 文档

如何使用 C# 库编辑 PDF 文件

为了编辑 PDF 文件,我们将使用 Aspose.PDF for .NET API,这是一款功能丰富、强大且易于使用的文档操作 API,适用于 net 平台。打开 NuGet 软件包管理器,搜索 Aspose.PDF 并安装。您也可以使用包管理器控制台中的以下命令。

通过 C# 编辑 PDF 文档


你需要 Aspose.PDF for .NET 才能在你的环境中试用代码。

1。使用 Document 实例加载 PDF。 1。使用搜索词作为参数创建 TextFragmentAbsorber 对象。 1。设置搜索选项。 1。循环浏览收集的每个片段进行编辑。 1。保存 PDF 文件。

编辑 PDF 文件-C#

var inputFile = Path.Combine(dataDir, "input.pdf");
var outputFile = Path.Combine(dataDir, "output.pdf");
var pdfDocument = new Aspose.Pdf.Document(inputFile);
var searchTerm = "Secret";
var textFragmentAbsorber = new Aspose.Pdf.Text.TextFragmentAbsorber(searchTerm);
var textSearchOptions = new Aspose.Pdf.Text.TextSearchOptions(true);
textFragmentAbsorber.TextSearchOptions = textSearchOptions;

pdfDocument.Pages.Accept(textFragmentAbsorber);
var textFragmentCollection = textFragmentAbsorber.TextFragments;
        
foreach (var textFragment in textFragmentCollection)
{
    var page = textFragment.Page;
    var annotationRectangle = textFragment.Rectangle;

    var annot = new Aspose.Pdf.Annotations.RedactionAnnotation(page, annotationRectangle)
    {
        FillColor = Aspose.Pdf.Color.Black
    };
    pdfDocument.Pages[textFragment.Page.Number].Annotations.Add(annot, true);
    annot.Redact();
}
pdfDocument.Save(outputFile);