How to Replace Text in a PDF

To replace text in a PDF using IronPDF Java, use the replaceText method with PageSelection to specify pages and provide the old and new text strings. This enables automated PDF content editing for fixing typos, updating information, and customizing templates.

Quickstart: Replace Text in PDF with Java

  1. Add IronPDF dependency to your project
  2. Create or load a PDF document
  3. Call pdf.replaceText(PageSelection.firstPage(), "oldText", "newText")
  4. Save the modified PDF with pdf.saveAs("output.pdf")

Introduction

IronPDF's text replacement functionality provides developers with powerful tools to modify existing PDF content programmatically. Whether you're updating product documentation, correcting errors in generated reports, or creating personalized documents from templates, the replaceText method offers precise control over content modifications. This feature is particularly valuable when working with PDF forms or when you need to maintain consistent formatting while updating specific text elements.

Start using IronPDF in your project today with a free trial.

First Step:
green arrow pointer

How Do I Replace Text on a Single Page?

To replace text, simply call the replaceText method. The method takes three parameters: PageSelection specifies the page, a string represents the old text, and the third parameter is the new text. In the example below, PageSelection.firstPage() retrieves the first page of the PDF. All instances of .NET6 are replaced with .NET7. The method throws a runtime exception if it cannot find the specified old text.

IronPDF console error showing Exception_RemoteException when replacing text '.NET7' - failed to find specified text

What Parameters Does replaceText Need?

```java :title=Replace Text Example 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 - required for production use
    License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");
    
    // Render HTML content into a PDF
    // This creates a new PDF from HTML content
    PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>.NET6</h1>");
    
    // Define the old and new text for replacement
    String oldText = ".NET6";  // Text to search for
    String newText = ".NET7";  // Replacement text
    
    // Replace all instances of oldText with newText on the first page
    // PageSelection.firstPage() targets only the first page (index 0)
    pdf.replaceText(PageSelection.firstPage(), oldText, newText);
    
    // Save the resulting PDF document
    pdf.saveAs("replaceText.pdf");

    } }

TipsAll page indexes follow zero-based indexing.

The replaceText method performs case-sensitive matching by default. "net6" and "NET6" are treated as different strings. When working with HTML to PDF conversions, ensure your search text matches exactly how it appears in the rendered PDF. For more advanced text operations, consider extracting text from PDFs to verify content before replacement.

What Does the Output Look Like?


How Can I Replace Text Across Multiple Pages?

Use the same replaceText method to replace text on multiple pages. Call the pageRange method from the PageSelection class and input a list of integers to specify pages. The example below replaces text only on the first and third pages. This approach works well for documents with consistent headers or footers on specific pages, or when updating information that appears in multiple locations throughout your PDF.

Which Pages Can I Target for Text Replacement?

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 - see https://ironpdf.com/java/licensing/
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // HTML content that will be converted to a 3-page PDF
        // Page breaks are created using CSS page-break-after property
        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 
        // Page numbers are zero-indexed: 0 = first page, 2 = third page
        List<Integer> pages = Arrays.asList(0, 2);

        // Replace the text on specified pages only
        // The second page (index 1) will remain unchanged
        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 - see https://ironpdf.com/java/licensing/
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // HTML content that will be converted to a 3-page PDF
        // Page breaks are created using CSS page-break-after property
        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 
        // Page numbers are zero-indexed: 0 = first page, 2 = third page
        List<Integer> pages = Arrays.asList(0, 2);

        // Replace the text on specified pages only
        // The second page (index 1) will remain unchanged
        pdf.replaceText(PageSelection.pageRange(pages), oldText, newText);

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

When creating multi-page PDFs from HTML, understanding custom PDF page sizes and page orientation settings helps ensure content displays correctly across all pages before applying text replacements.

What Happens When I Skip Pages During Replacement?


What Page Selection Options Are Available?

Using PageSelection methods allows developers to specify which pages to modify. A complete list of parameters is below.

Please noteThe PageSelection class methods are static. No instance creation is needed. Page indexes start at 0.

Which Methods Target Single vs Multiple Pages?

  • allPages: Selects all pages of the PDF
  • firstPage: Selects the first page of the PDF
  • lastPage: Selects the last page of the PDF
  • pageRange(int startIndex, int endIndex): Specifies a range of pages (e.g., 0 to 2 selects pages 13)
  • pageRange(List<Integer> pageList): Selects specific pages from a list (e.g., [0, 2] selects pages 1 and 3)
  • singlePage(int pageIndex): Specifies a single page of the PDF

When Should I Use Each PageSelection Method?

Use firstPage() or lastPage() for quick edits to document headers and footers. Choose pageRange() when updating multiple sequential pages like chapters. Select singlePage() for targeted corrections, and apply allPages() for global find-and-replace operations across the entire document.

When working with merged PDFs, use pageRange() to update only pages from a specific source document. Similarly, when handling documents with bookmarks and outlines, target specific sections using their page ranges.

Best Practices for Text Replacement

When implementing text replacement in Java applications, consider these important factors:

Performance Optimization: Load your license key once at application startup rather than before each operation. This improves performance when processing multiple documents. Learn more about using license keys effectively.

Error Handling: Wrap text replacement operations in try-catch blocks to handle potential exceptions gracefully. The most common exception occurs when the specified text cannot be found. Consider implementing a validation step by first extracting text from the PDF to verify its presence.

Preserving Formatting: The replaceText method maintains original text formatting, including font family, size, color, and style. This makes it ideal for updating content while preserving visual consistency. For more control over formatting, consider regenerating the PDF from HTML using custom render settings.

Working with Complex Documents: For PDFs containing forms, use specialized methods for filling PDF forms rather than text replacement. This ensures form field functionality remains intact.

Common Use Cases

Text replacement in PDFs serves numerous practical applications across different industries:

Template-Based Document Generation: Create reusable PDF templates with placeholder text that can be replaced with actual data. This approach works well for invoices, contracts, and reports where layout remains consistent but content varies.

Batch Document Updates: Update company information, addresses, or contact details across multiple PDFs simultaneously. This is particularly useful during rebranding or when regulatory information changes.

Localization and Translation: Replace text content to create localized versions of documents for different markets. Combine this with custom fonts support to ensure proper character rendering for various languages.

Dynamic Content Personalization: Personalize PDFs for individual recipients by replacing placeholder text with customer-specific information, creating a more engaging experience for document recipients.

Frequently Asked Questions

How do I replace text in a PDF using Java?

To replace text in a PDF using IronPDF Java, use the replaceText method. Simply call pdf.replaceText(PageSelection.firstPage(), "oldText", "newText") to replace all instances of the old text with the new text on the specified page. IronPDF will automatically find and replace all occurrences while maintaining the original formatting.

What parameters does the replaceText method require?

The replaceText method in IronPDF requires three parameters: PageSelection to specify which pages to modify, a string containing the text to find, and a string with the replacement text. For example, pdf.replaceText(PageSelection.firstPage(), ".NET6", ".NET7") replaces all instances of '.NET6' with '.NET7' on the first page.

Can I replace text on specific pages only?

Yes, IronPDF allows you to replace text on specific pages using the PageSelection parameter. You can use PageSelection.firstPage() for the first page, PageSelection.lastPage() for the last page, or PageSelection.pageRange() to specify a custom range of pages where the text replacement should occur.

What happens if the text I want to replace isn't found?

When IronPDF cannot find the specified text to replace, it throws a runtime exception (Exception_RemoteException). This ensures you're aware when a replacement operation fails, allowing you to handle the error appropriately in your Java application.

Can I use this feature to update templates or fix typos in PDFs?

Absolutely! IronPDF's text replacement functionality is perfect for updating templates, fixing typos, and customizing documents. Whether you're correcting errors in generated reports, updating product documentation, or creating personalized documents from templates, the replaceText method provides precise control over content modifications.

Does replacing text maintain the original PDF formatting?

Yes, IronPDF's replaceText method maintains the original formatting of your PDF document. When you replace text, the new content inherits the same font, size, color, and styling as the original text, ensuring your document's appearance remains consistent after modifications.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity ...

Read More
Ready to Get Started?
Version: 2025.12 just released