Easy 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.

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

Полный код

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 100-day 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 license:
			' 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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.com или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.