How to Replace Text in a PDF

This article was translated from English: Does it need improvement?
Translated
View the article in English

The feature to replace text in a PDF is extremely useful for making quick and precise edits to content, such as correcting typos, updating information, or customizing templates for different purposes. This can save a significant amount of time and effort, especially when dealing with documents that require frequent revisions or personalization.

IronPDF provides a feature for replacing text in PDFs. This feature makes IronPDF an invaluable tool for developers and professionals who need to automate or customize PDF content.

Quickstart: Replace Text in PDF with IronPDF

Begin replacing text in your PDFs effortlessly using IronPDF. With just a few lines of code, you can update or customize your documents swiftly. This example demonstrates how to replace text across all pages of a PDF. Simply load your PDF, specify the text to find and replace, and save the updated document. Perfect for correcting typos or updating information in templates, IronPDF makes text replacement in C# a seamless experience. Dive into this guide to transform your PDF handling efficiency in .NET environments.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    IronPdf.PdfDocument.FromFile("example.pdf")
        .ReplaceTextOnAllPages("old text", "new text")
        .SaveAs("updated.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Replace Text Example

The 'replace text' action can be applied to any PdfDocument object, whether it's newly rendered or imported. You can utilize the ReplaceTextOnAllPages method by providing both the old and new text for replacement. If the method cannot locate the specified old text, it will raise an exception with the message 'Error while replacing text: failed to find text '.NET6'.'

In the code example below, we demonstrate how to replace text on a newly rendered PDF document containing the text '.NET6'.

Code

:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text-all-page.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>");

string oldText = ".NET6";
string newText = ".NET7";

// Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText);

pdf.SaveAs("replaceText.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>")

Private oldText As String = ".NET6"
Private newText As String = ".NET7"

' Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText)

pdf.SaveAs("replaceText.pdf")
$vbLabelText   $csharpLabel

Replace Text with Newline

The replace text action supports newline characters, allowing you to replace old text with a new string that includes built-in newlines for better formatting and visual clarity.

To achieve this, add newline characters (\n) to the new string. Using the example above, we replace newText with .NET7\nnewline instead of just .NET7.


Replace Text on Specified Pages

For greater accuracy in replacing text within a document, IronPDF also offers options to replace text on a single page or multiple pages, depending on your requirements. You can use the ReplaceTextOnPage method to replace text on a specific page and the ReplaceTextOnPages method to replace text on multiple specified pages of the document.

ConsejosAll page indexes follow zero-based indexing.

Replace Text on a Single Page

:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text-on-single-page.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>");

string oldText = ".NET6";
string newText = ".NET7";

// Replace text on page 1
pdf.ReplaceTextOnPage(0, oldText, newText);

pdf.SaveAs("replaceTextOnSinglePage.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>")

Private oldText As String = ".NET6"
Private newText As String = ".NET7"

' Replace text on page 1
pdf.ReplaceTextOnPage(0, oldText, newText)

pdf.SaveAs("replaceTextOnSinglePage.pdf")
$vbLabelText   $csharpLabel

Replace Text on Multiple Pages

:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text-on-multiple-pages.cs
using IronPdf;

string html = @"<p> .NET6 </p>
<p> This is 1st Page </p>
<div style = 'page-break-after: always;'></div>
<p> This is 2nd Page</p>
<div style = 'page-break-after: always;'></div>
<p> .NET6 </p>
<p> This is 3rd Page</p>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

string oldText = ".NET6";
string newText = ".NET7";

int[] pages = { 0, 2 };

// Replace text on page 1 & 3
pdf.ReplaceTextOnPages(pages, oldText, newText);

pdf.SaveAs("replaceTextOnMultiplePages.pdf");
Imports IronPdf

Private html As String = "<p> .NET6 </p>
<p> This is 1st Page </p>
<div style = 'page-break-after: always;'></div>
<p> This is 2nd Page</p>
<div style = 'page-break-after: always;'></div>
<p> .NET6 </p>
<p> This is 3rd Page</p>"

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

Private oldText As String = ".NET6"
Private newText As String = ".NET7"

Private pages() As Integer = { 0, 2 }

' Replace text on page 1 & 3
pdf.ReplaceTextOnPages(pages, oldText, newText)

pdf.SaveAs("replaceTextOnMultiplePages.pdf")
$vbLabelText   $csharpLabel

Output PDF


Use Custom Font

The same ReplaceTextOnPage method also allows you to use a custom font and size. First, the font needs to be added to the PDF, after which you can pass the font name as a parameter to the method. In the following example, I will use the Pixelify Sans Font.

:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text-custom-font.cs
using IronPdf;
using System.IO;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Use custom font .NET6</h1>");

string oldText = ".NET6";
string newText = ".NET7";

// Add custom font
byte[] fontByte = File.ReadAllBytes(@".\PixelifySans-VariableFont_wght.ttf");
var pdfFont = pdf.Fonts.Add(fontByte);

// Use custom font
pdf.ReplaceTextOnPage(0, oldText, newText, pdfFont, 24);

pdf.SaveAs("replaceCustomText.pdf");
Imports IronPdf
Imports System.IO

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Use custom font .NET6</h1>")

Private oldText As String = ".NET6"
Private newText As String = ".NET7"

' Add custom font
Private fontByte() As Byte = File.ReadAllBytes(".\PixelifySans-VariableFont_wght.ttf")
Private pdfFont = pdf.Fonts.Add(fontByte)

' Use custom font
pdf.ReplaceTextOnPage(0, oldText, newText, pdfFont, 24)

pdf.SaveAs("replaceCustomText.pdf")
$vbLabelText   $csharpLabel

Result

Use custom font

Preguntas Frecuentes

¿Cómo puedo reemplazar texto en un PDF usando C#?

Puedes reemplazar texto en un PDF usando IronPDF utilizando el método ReplaceTextOnAllPages para modificar el texto en todo el documento. Si necesitas reemplazar texto en páginas específicas, usa los métodos ReplaceTextOnPage o ReplaceTextOnPages.

¿Puedo reemplazar texto en un PDF con nuevo contenido que incluya saltos de línea?

Sí, IronPDF admite reemplazar texto con nuevo contenido que incluya caracteres de nueva línea. Puedes incluir caracteres de nueva línea en el texto de reemplazo para mejorar el formato y la claridad en tus documentos PDF.

¿Qué debo hacer si mi texto especificado no se encuentra durante el proceso de reemplazo?

Si el método ReplaceTextOnAllPages no puede encontrar el texto antiguo especificado, se generará una excepción con un mensaje indicando el error. Asegúrate de que el texto que deseas reemplazar esté correctamente especificado y exista en el documento.

¿Es posible usar fuentes personalizadas al reemplazar texto en un PDF?

Sí, puedes usar fuentes personalizadas al reemplazar texto en un PDF con IronPDF. Primero, agrega la fuente deseada al PDF y luego especifica el nombre de la fuente como un parámetro en el método ReplaceTextOnPage.

¿Dónde puedo descargar la biblioteca IronPDF para el reemplazo de texto en PDFs?

Puedes descargar la biblioteca IronPDF C# desde el gestor de paquetes NuGet en https://www.nuget.org/packages/IronPdf/.

¿En qué formato se guardará el PDF editado después del reemplazo de texto?

Después de reemplazar texto en un PDF usando IronPDF, el documento modificado puede guardarse en el formato PDF estándar usando el método SaveAs.

¿Cómo puedo reemplazar texto en múltiples páginas específicas en un PDF?

Para reemplazar texto en múltiples páginas específicas en un PDF, usa el método ReplaceTextOnPages de IronPDF. Esto te permite especificar las páginas donde el texto debe ser reemplazado, usando indexación de páginas basada en cero.

¿IronPDF es totalmente compatible con .NET 10 al utilizar las funciones de búsqueda y reemplazo de texto?

Sí. IronPDF sigue siendo totalmente compatible con .NET 10, y sus funciones de búsqueda y reemplazo de texto (como ReplaceTextOnAllPages , ReplaceTextOnPage y métodos relacionados) funcionan a la perfección en proyectos .NET 10 sin necesidad de soluciones alternativas. ([ironpdf.com](https://ironpdf.com/blog/net-help/net-10-features/?utm_source=openai))

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado