使用 C# 編輯 PDF

PDF 文檔敏感的編輯信息。在 .NET 使用 Aspose.PDF 以編程方式修改 PDF 文件

如何使用 C# 庫編輯 PDF 文件

為了編輯 PDF 文件,我們將使用 Aspose.PDF for .NET API,它是一款功能豐富、強大且易於使用的文件操作 API,適用於 net 平台。開啟 NuGet 套件管理器,搜尋 Aspose.PDF 並安裝。您也可以在套件管理器控制台中使用下列命令。

透過 C# 編輯 PDF 文件


您需要 Aspose.PDF for .NET 才能在您的環境中測試程式碼。

1.載入帶有「文件」實例的 PDF。 1.使用搜索詞作為引數創建文本 FragmentAbsorber 對象。 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);