How to Replace Text in a PDF

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

Swapping out text within a PDF is incredibly convenient for swiftly and accurately editing content. It's perfect for fixing typos, refreshing information, or tailoring templates for specific needs. This feature is a real-time-saver, particularly for documents that need frequent updates or personalized touches.

IronPDF offers a text replacement feature for PDFs, making it an indispensable tool for developers and professionals seeking to automate or customize PDF content.

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Replace Text Example

To replace text, we can simply call the replaceText method. The method takes three parameters: the first one is PageSelection, which specifies the page; the second is a string representing the old text; and the third is the new text. For this example below, we will call the PageSelection.firstPage() method, which retrieves the first page of the PDF. We will replace all instances of '.NET6' with '.NET7'. You will encounter a runtime exception if the method cannot find the specified old text. Alt text

Code

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.edit.PageSelection;
import java.io.IOException;

/**
 * Main application class for demonstrating how to replace text in a PDF.
 */
public class App {

    public static void main(String[] args) throws IOException {

        // Set the IronPDF license key
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // Render HTML content into a PDF
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>.NET6</h1>");

        // Define the old and new text for replacement
        String oldText = ".NET6";
        String newText = ".NET7";

        // Replace all instances of oldText with newText on the first page
        pdf.replaceText(PageSelection.firstPage(), oldText, newText);

        // Save the resulting PDF document
        pdf.saveAs("replaceText.pdf");
    }
}
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.edit.PageSelection;
import java.io.IOException;

/**
 * Main application class for demonstrating how to replace text in a PDF.
 */
public class App {

    public static void main(String[] args) throws IOException {

        // Set the IronPDF license key
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // Render HTML content into a PDF
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>.NET6</h1>");

        // Define the old and new text for replacement
        String oldText = ".NET6";
        String newText = ".NET7";

        // Replace all instances of oldText with newText on the first page
        pdf.replaceText(PageSelection.firstPage(), oldText, newText);

        // Save the resulting PDF document
        pdf.saveAs("replaceText.pdf");
    }
}
JAVA

ConsejosAll page indexes follow zero-based indexing.

Output PDF


Replace Text on Multiple Pages

We use the same replaceText method to replace text on multiple pages. But this time, we call the pageRange method from the PageSelection class and input a list of Integers to specify that we want to replace the text only on the first and third pages.

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.edit.PageSelection;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Main application class for demonstrating how to replace text on multiple pages of a PDF.
 */
public class App {

    public static void main(String[] args) throws IOException {

        // Set the IronPDF license key
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // HTML content that will be converted to a 3-page PDF
        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>";

        // Render the HTML content into a PDF
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);

        // Define the old and new text for replacement
        String oldText = ".NET6";
        String newText = ".NET7";

        // Define the pages where text replacement should occur (first and third page)
        List<Integer> pages = Arrays.asList(0, 2);

        // Replace the text on specified pages
        pdf.replaceText(PageSelection.pageRange(pages), oldText, newText);

        // Save the resulting PDF document
        pdf.saveAs("replaceTextOnMultiplePages.pdf");
    }
}
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.edit.PageSelection;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Main application class for demonstrating how to replace text on multiple pages of a PDF.
 */
public class App {

    public static void main(String[] args) throws IOException {

        // Set the IronPDF license key
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // HTML content that will be converted to a 3-page PDF
        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>";

        // Render the HTML content into a PDF
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);

        // Define the old and new text for replacement
        String oldText = ".NET6";
        String newText = ".NET7";

        // Define the pages where text replacement should occur (first and third page)
        List<Integer> pages = Arrays.asList(0, 2);

        // Replace the text on specified pages
        pdf.replaceText(PageSelection.pageRange(pages), oldText, newText);

        // Save the resulting PDF document
        pdf.saveAs("replaceTextOnMultiplePages.pdf");
    }
}
JAVA

Output PDF


Explore PageSelection Class

Like the example above, using the PageSelection methods allows developers to specify which pages to replace text within. A complete list of the parameters is below.

Por favor notaSince the PageSelection class methods are static, you do not need to create a new instance to use its methods. The page index starts at 0.

  • allPages: A method that selects all pages of the PDF.
  • firstPage: A method that selects the first page of the PDF.
  • lastPage: A method that selects the last page of the PDF.
  • pageRange(int startIndex, int endIndex): A method that specifies a range of pages to select. For example, setting startIndex = 0 and endIndex = 2 selects pages 1 to 3.
  • pageRange(List<Integer> pageList): A method that specifies which pages to select; from the example above, if the list contains the integers 0 and 2, the method selects only the first and third page, skipping the second page.
  • singlePage(int pageIndex): A method that specifies a single page of the PDF.

Preguntas Frecuentes

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

Puede reemplazar texto en un PDF usando IronPDF for Java descargando la biblioteca, cargando un PDF existente o creando uno nuevo, y utilizando el método replaceText. Este método le permite especificar el texto a reemplazar y el nuevo texto, ya sea en páginas específicas o en todo el documento.

¿Qué pasos están involucrados en reemplazar texto en un PDF con IronPDF?

Reemplazar texto en un PDF usando IronPDF implica cinco pasos principales: descargar la biblioteca Java, cargar o crear un PDF, usar el método replaceText, especificar páginas con PageSelection, y guardar el PDF editado.

¿Puedo reemplazar texto en páginas específicas de un PDF usando Java?

Sí, puede reemplazar texto en páginas específicas de un PDF usando IronPDF al utilizar la clase PageSelection. Esta clase ofrece métodos como pageRange, singlePage, y otros para dirigir páginas específicas para el reemplazo de texto.

¿Qué ocurre si el texto a reemplazar no se encuentra en el PDF?

Si el texto especificado para ser reemplazado no se encuentra en el PDF, IronPDF encontrará una excepción de ejecución durante el proceso de reemplazo, indicando que el texto no pudo ser localizado.

¿Cómo guardo un PDF modificado después del reemplazo de texto en Java?

Después de reemplazar texto en un PDF usando IronPDF, puede guardar el documento modificado llamando al método saveAs en el objeto PdfDocument, especificando el nombre de archivo deseado para el PDF de salida.

¿Es necesario instanciar la clase PageSelection para usar sus métodos en IronPDF?

No, no es necesario instanciar la clase PageSelection para usar sus métodos porque son estáticos. Puede llamar directamente a métodos como allPages, firstPage, y otros sin crear una nueva instancia.

¿Cómo afecta la indexación basada en cero a la selección de páginas en IronPDF?

En IronPDF, la selección de páginas utiliza indexación basada en cero, lo que significa que los números de página comienzan desde 0. Esto es importante para especificar con precisión qué páginas dirigir al usar los métodos PageSelection para el reemplazo de texto.

¿Cuáles son algunos métodos proporcionados por la clase PageSelection en IronPDF?

La clase PageSelection en IronPDF proporciona métodos como allPages, firstPage, lastPage, pageRange, y singlePage, que le permiten seleccionar eficientemente páginas específicas para el reemplazo de texto en un PDF.

¿IronPDF admite .NET 10 para reemplazar texto en archivos PDF? ¿Existen diferencias específicas según la versión?

Sí, IronPDF es compatible con .NET 10 para reemplazar texto. Los métodos como ReplaceTextOnAllPages , ReplaceTextOnPage y ReplaceTextOnPages funcionan en .NET 10 de forma similar a las versiones anteriores de .NET. Además, en versiones recientes como la 2024.12.9 se han añadido mejoras como la compatibilidad con caracteres de nueva línea y sobrecargas que aceptan objetos PdfFont . ([componentsource.com](https://www.componentsource.com/product/ironpdf/releases/2872686?utm_source=openai))

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

Leer más
¿Listo para empezar?
Versión: 2025.11 recién lanzado