Redact PDF using C#

PDF document sensitive redaction information. Use Aspose.PDF for .NET to modify PDF documents programmatically

How to Redact PDF File Using C# Library

In order to redact PDF file, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Redact PDF documents via C#


You need Aspose.PDF for .NET to try the code in your environment.

  1. Load the PDF with an instance of Document.
  2. Create TextFragmentAbsorber object with search terms as argument.
  3. Set Search Options.
  4. Loop through each fragment collect to redact.
  5. Save PDF file.

Redact PDF Files - 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);