How to Replace Text in a PDF
IronPDF for Java gives developers direct control over existing PDF content through the replaceText method. Whether you need to correct a typo in a batch of generated reports, swap version numbers across template documents, or personalize contracts with customer-specific data, the method accepts a page selection, a search string, and a replacement string and handles the rest. This guide covers single-page replacement, multi-page targeting, every available PageSelection option, and practical patterns for template-driven workflows.
Quickstart: Replace Text in a PDF
Add the IronPDF dependency, load or render a PDF, call replaceText, and save the result:
```java :title=Quickstart Replace Text //:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text/quickstart.java import com.ironsoftware.ironpdf.*; import com.ironsoftware.ironpdf.edit.PageSelection; import java.io.IOException;
public class App { public static void main(String[] args) throws IOException { License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01"); PdfDocument pdf = PdfDocument.renderHtmlAsPdf(""); pdf.replaceText(PageSelection.firstPage(), ".NET6", ".NET7"); pdf.saveAs("replaceText.pdf"); } }
<div class="hsg-featured-snippet">
<h3>Minimal Workflow (5 steps)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="download-modal" href="#download-modal">Download the Java library to replace text in a PDF</a></li>
<li>Load an existing PDF or render one from HTML</li>
<li>Call <code>pdf.replaceText(PageSelection, oldText, newText)</code> to replace on targeted pages</li>
<li>Use <code>PageSelection</code> methods to control which pages are modified</li>
<li>Save and export the updated PDF with <code>pdf.saveAs("output.pdf")</code></li>
</ol>
</div>
## How Do I Replace Text on a Single Page?
The `replaceText` method accepts three arguments: a `PageSelection` that targets one or more pages, the exact text to find, and the replacement string. To target the first page, pass `PageSelection.firstPage()`. All instances of the search string on that page are replaced in a single call. If the text cannot be found on the targeted pages, the method throws a runtime exception. The screenshot below shows what that exception looks like in the console.

### What Parameters Does replaceText Accept?
The method signature is `replaceText(PageSelection pageSelection, String oldText, String newText)`. Matching is case-sensitive by default: `"net6"` and `"NET6"` are treated as different strings. Verify the exact casing in the rendered PDF before calling the method. You can confirm the exact text by [extracting the PDF's text content](https://ironpdf.com/java/examples/extract-image-from-pdf/) first. The IronPDF Java dependency is published on [Maven Central](https://central.sonatype.com/artifact/com.ironsoftware/ironpdf) and requires Java 8 or later.
```java :title=Replace Text on First Page
//:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text/replace-text-single-page.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.edit.PageSelection;
import java.io.IOException;
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 document
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>.NET6</h1>");
// Define the search and replacement strings
String oldText = ".NET6";
String newText = ".NET7";
// Replace all instances of oldText on the first page only
// PageSelection.firstPage() targets page index 0
pdf.replaceText(PageSelection.firstPage(), oldText, newText);
// Save the modified PDF
pdf.saveAs("replaceText.pdf");
}
}
The replaceText method integrates naturally with IronPDF's HTML to PDF conversion workflow. Render the HTML template first, then apply text replacement to inject dynamic values. This keeps your HTML clean while still producing personalized output. For documents loaded from disk, pass the file path to PdfDocument.fromFile instead of using renderHtmlAsPdf.
What Does the Output Look Like?
How Do I Replace Text Across Multiple Pages?
To target specific pages rather than just the first, pass a list of zero-indexed page numbers to PageSelection.pageRange(List<Integer>). The method replaces the search text on every page in the list and leaves all other pages untouched. This pattern suits documents with consistent headers or footers on known pages, or batch-generated reports where a version string only appears on certain pages.
Which Pages Are Modified When Using a Page List?
In the example below, a three-page PDF is created from HTML. The replacement runs on pages 0 and 2 (the first and third pages). Page 1 (the second page) keeps the original text unchanged. Page indexes always start at 0, consistent with Java's zero-based array conventions.
```java :title=Replace Text on Multiple Specific Pages //:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text/replace-text-multiple-pages.java import com.ironsoftware.ironpdf.*; import com.ironsoftware.ironpdf.edit.PageSelection; import java.io.IOException; import java.util.Arrays; import java.util.List;
public class App {
public static void main(String[] args) throws IOException {
// Set the IronPDF license key
License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");
// Build a 3-page PDF from HTML using CSS page breaks
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>";
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
String oldText = ".NET6";
String newText = ".NET7";
// Pages are zero-indexed: 0 = first page, 2 = third page
// Page index 1 (second page) is intentionally excluded
List<Integer> pages = Arrays.asList(0, 2);
pdf.replaceText(PageSelection.pageRange(pages), oldText, newText);
pdf.saveAs("replaceTextOnMultiplePages.pdf");
}
}
Please noteAll page indexes in IronPDF follow zero-based indexing. Page `0` is the first page, page `1` is the second, and so on.
When creating multi-page PDFs from HTML, use the [CSS `page-break-after` property](https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-after) to control where page boundaries fall. Setting the right [custom paper size](https://ironpdf.com/java/examples/custom-pdf-paper-size/) and [page orientation](https://ironpdf.com/java/examples/pdf-page-orientation/) before rendering ensures the content positions match your expectations when text replacement runs. After saving, verify the output by opening the PDF and confirming only the targeted pages changed.
### What Does the Output Look Like?
<iframe loading="lazy" src="/static-assets/ironpdf-java/howto/find-replace-text/replaceTextOnMultiplePages.pdf" width="100%" height="400px"></iframe>
<hr>
## What Page Selection Options Are Available?
The `PageSelection` class provides static factory methods that cover every common targeting pattern. No instance creation is needed; call the methods directly on the class. All indexes are zero-based.
### Which Methods Target Single vs. Multiple Pages?
<table class="content__data-table" data-content-table>
<caption>PageSelection factory methods for the replaceText API</caption>
| Method | Description |
|---|---|
| `PageSelection.allPages()` | Selects every page in the document |
| `PageSelection.firstPage()` | Selects page at index `0` |
| `PageSelection.lastPage()` | Selects the final page regardless of document length |
| `PageSelection.singlePage(int pageIndex)` | Selects one specific page by zero-based index |
| `PageSelection.pageRange(int startIndex, int endIndex)` | Selects a contiguous range from `startIndex` to `endIndex` inclusive |
| `PageSelection.pageRange(List<Integer> pageList)` | Selects pages at any arbitrary set of indexes (e.g., `[0, 2]` selects pages 1 and 3) |
</table>
### When Should I Use Each PageSelection Method?
`allPages()` is the simplest choice for a global find-and-replace: every instance of the target text across the entire document is replaced in one call. Use `firstPage()` or `lastPage()` for quick edits to cover pages or last-page footers without touching the body. Choose `pageRange(int, int)` when the text appears on a sequential set of pages such as a chapter or section. Use `pageRange(List<Integer>)` when the target pages are non-contiguous; for example, when replacing a version string that only appears on pages 1, 3, and 7.
When working with [merged PDFs](https://ironpdf.com/java/examples/split-pdfs/) or documents that include [bookmarks and outlines](https://ironpdf.com/java/how-to/bookmarks/), identify the page range for each logical section first, then apply targeted replacements to avoid modifying shared headers or footers accidentally. The [IronPDF for Java API reference](https://ironpdf.com/object-reference/api/) lists all `PageSelection` overloads with full parameter documentation.
ImportantWrap `replaceText` calls in a try-catch block. The method throws a runtime exception when the specified search text is not found on any of the targeted pages. A validation step (extracting text and confirming the string is present) prevents unexpected failures in production.
### How Do I Replace Text on All Pages at Once?
`PageSelection.allPages()` performs a document-wide replacement in a single call, which is the most efficient approach for global token substitution. The example below loads a PDF from disk and replaces every occurrence of a placeholder token across the entire document:
```java :title=Replace Text on All Pages
//:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text/replace-text-all-pages.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.edit.PageSelection;
import java.io.IOException;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) throws IOException {
// Set the IronPDF license key
License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");
// Load an existing PDF from disk
PdfDocument pdf = PdfDocument.fromFile(Paths.get("contract-template.pdf"));
// Replace the placeholder token on every page simultaneously
// This is equivalent to calling replaceText for each page individually
pdf.replaceText(PageSelection.allPages(), "{{VERSION}}", "2.0");
// Save the updated document
pdf.saveAs("contract-v2.pdf");
}
}
This pattern pairs naturally with template-driven workflows where the same placeholder appears in headers, footers, or body text across many pages. For single-page documents, allPages() and firstPage() produce identical results. Prefer allPages() when the page count may vary at runtime.
How Do I Handle Common Text Replacement Scenarios?
Text replacement in Java applications covers several patterns that go beyond a simple search-and-replace. Understanding how the method behaves in each case prevents bugs before they appear in production.
How Does Case-Sensitive Matching Affect Results?
replaceText performs exact, case-sensitive matching. The strings "Version 1.0", "version 1.0", and "VERSION 1.0" are treated as three distinct values. Before running a replacement on a document loaded from disk, confirm the exact casing by reviewing the original source or by extracting text from the PDF and inspecting it programmatically.
How Do I Replace Text in PDF Forms?
PDFs that contain interactive form fields store their text values separately from the document's content stream, as defined in the PDF specification. The replaceText method operates on the content stream and does not modify form field values. To update text inside form fields, use IronPDF's dedicated form creation and editing API instead. Mixing both approaches in the same document is safe: form field updates and content-stream replacements do not interfere with each other.
How Do I Update Text in Template-Based Workflows?
A common pattern is to maintain a PDF template with placeholder tokens (for example {{CUSTOMER_NAME}} or [INVOICE_DATE]) and replace them at runtime with actual values. Call replaceText once per placeholder, using PageSelection.allPages() so the replacement covers every location the token appears. For documents generated from HTML, this workflow works equally well with renderHtmlAsPdf followed by a series of replacement calls. Combine this with PDF watermarking or backgrounds and foregrounds to add branding or confidentiality markings to the final output.
What Are the Next Steps for PDF Text Replacement in Java?
This guide covered single-page replacement with PageSelection.firstPage(), selective multi-page replacement with PageSelection.pageRange(), document-wide replacement with PageSelection.allPages(), and the full set of PageSelection factory methods. The same replaceText API works whether the document was rendered from HTML, loaded from disk, or assembled by merging multiple sources.
Start a free trial of IronPDF for Java and run the code examples above against your own documents. When you are ready to deploy to production, review the licensing options. Licenses are per-developer and include one year of product updates.
Ready to see what else IronPDF for Java can do? Browse the complete IronPDF for Java how-to guides for tutorials on PDF generation, annotation, digital signatures, compression, and more.
Frequently Asked Questions
How do I replace text in a PDF using Java?
Use IronPDF's replaceText method. Call pdf.replaceText(PageSelection.firstPage(), "oldText", "newText") to replace all instances of the old text on the specified page. IronPDF finds and replaces every occurrence while preserving the original formatting.
What parameters does the replaceText method accept?
The method accepts three parameters: a PageSelection to specify which pages to modify, a String with the text to find, and a String with the replacement text. For example, pdf.replaceText(PageSelection.firstPage(), ".NET6", ".NET7") replaces all instances on the first page.
Can I replace text on specific pages only?
Yes. Use PageSelection.firstPage() for page 0, PageSelection.lastPage() for the final page, PageSelection.singlePage(n) for any page by zero-based index, or PageSelection.pageRange() with a list of integers for non-contiguous pages.
What happens if the text to replace is not found?
IronPDF throws a runtime exception (Exception_RemoteException) when the target text cannot be found on the targeted pages. Wrap the call in a try-catch block and optionally extract the PDF text first to verify the string exists before calling replaceText.
Is text matching case-sensitive?
Yes. The replaceText method performs exact, case-sensitive matching. The strings "Version 1.0", "version 1.0", and "VERSION 1.0" are treated as three distinct values. Verify the exact casing before calling the method.
Does replaceText modify form field values?
No. The replaceText method operates on the PDF content stream and does not modify interactive form field values. To update form fields, use IronPDF's dedicated form editing API via the PdfDocument form methods.
How do I replace a token on every page at once?
Use PageSelection.allPages() as the first argument to replaceText. This replaces every instance of the target text across all pages in a single call, which is the preferred approach for template-driven workflows with document-wide placeholders.


