Find and replace text on PDF document in C#

Spire.PDF supports to find and replace the text in all the pages of PDF document. This article is going to show you how to replace text in the first page of PDF document in C#.

Step 1: Load the sample document file.

PdfDocument doc = new PdfDocument();

Step 2: Searched the text “Spire.PDF for .NET” from the first page of the sample document.

PdfPageBase page = doc.Pages[0];
PdfTextFindCollection collection = page.FindText("Spire.PDF for .NET", TextFindParameter.IgnoreCase);

Step 3: Use the new string “E-iceblue Spire.PDF” to replace the searched text and sent the font and color for the new string.

String newText = "E-iceblue Spire.PDF";
//Creates a brush
PdfBrush brush = new PdfSolidBrush(Color.DarkBlue);
//Defines a font
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Regular));

RectangleF rec;
foreach (PdfTextFind find in collection.Finds)
    // Gets the bound of the found text in page
    rec = find.Bounds;
    page.Canvas.DrawRectangle(PdfBrushes.White, rec);
    page.Canvas.DrawString(newText, font, brush, rec);


Step 4: Save the document to file.


Sample PDF document:

Find and replace text on PDF document in C#

Effective screenshot after replaced the searched text on PDF.

Find and replace text on PDF document in C#