Text Replacement in PDFs with C# and .NET

Are you looking for an efficient way to find and replace text in PDF documents using C# and .NET? Look no further than Sautinsoft, a powerful tool that simplifies the process and allows you to seamlessly modify text within your PDFs.

With Sautinsoft, you can easily locate specific text within your PDF document and replace it with new content. This can be incredibly useful for updating outdated information, correcting errors, or customizing documents to meet your specific needs.

Step-by-step guide:

  1. Add SautinSoft.PDF from NuGet.
  2. Load a PDF document and iterate by all pages.
  3. Find the word "North".
  4. Delete (redact) the text "North".
  5. Draw the text "South" by orange font, using the coordinates.
  6. Save the document in PDF format.

Output result:

Complete code

using System;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Find and Replace text in PDF document using C# and .NET
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/find-and-replace-text-in-pdf-document-csharp-dotnet.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            string inpFile = Path.GetFullPath(@"..\..\..\simple text.pdf");
            string outFile = Path.GetFullPath("Result.pdf");

            using (PdfDocument document = PdfDocument.Load(inpFile))
            {
                foreach (var page in document.Pages)
                {
                    var search = page.Content.GetText().Find("North");
                    foreach (var text in search)
                    {
                        var element = text.Elements.First();
                        var font = element.Format.Text.Font;
                        double size = Math.Min(text.Bounds.Height, font.Size * element.TextTransform.M11);

                        using (var formattedText = new PdfFormattedText() { Font = font, Color = PdfColor.FromRgb(1, 0, 0), FontSize = size })
                        {
                            formattedText.Append("South");
                            page.Content.DrawText(formattedText, new PdfPoint(text.Bounds.Left, text.Bounds.Bottom));
                        }
                        text.Redact();
                    }
                }
                document.Save(outFile);
            }
            // Show the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Find and Replace text in PDF document using C# and .NET
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/find-and-replace-text-in-pdf-document-csharp-dotnet.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free trial key:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Dim inpFile As String = Path.GetFullPath("..\..\..\simple text.pdf")
			Dim outFile As String = Path.ChangeExtension(inpFile, ".res.pdf")

			Using document As PdfDocument = PdfDocument.Load(inpFile)
				' Assume we want to find the word "North"
				' and replace it to the "South".
				Dim textFrom As String = "North"
				Dim textTo As String = "South"

				' Iterate by all pages
				For Each page In document.Pages
					' Find the text.
					Dim texts = page.Content.GetText().Find(textFrom)

					' Get the text coordinates and font from 1st Element;
					' Draw the new text.
					For Each PDFtext In texts
						For Each el In PDFtext.Elements
							' Get the text formatting, coordinates;
							' Draw the new text "South".
							Using formattedText = New PdfFormattedText()
								formattedText.Font = el.Format.Text.Font
								' Set "orange" color
								formattedText.Color = PdfColor.FromRgb(1, 0.647, 0)
								formattedText.AppendLine(textTo)
								page.Content.DrawText(formattedText, New PdfPoint(PDFtext.Bounds.Left, PDFtext.Bounds.Bottom - PDFtext.Bounds.Height))
							End Using
							Exit For
						Next el
						' Remove the text.
						PDFtext.Redact()
					Next PDFtext
				Next page
				document.Save(outFile)
			End Using
			' Show the result.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.