如何在PDF中替換文字 Copy for LLMsCopy for LLMs Copy page as Markdown for LLMs
# 如何在PDF中替換文字
IronPDF for Java讓開發者通過`replaceText`方法直接控制現有的PDF內容。 無論您需要在一批生成的報告中更正拼寫錯誤、更換模板文件中的版本號,還是用客戶特定資料來個性化合同,該方法接受頁面選擇、搜索字串和替換字串,並處理其餘的工作。本指南涵蓋了單頁替換、多頁目標、每個可用的`PageSelection`選項以及適用於模板驅動工作流的實用模式。
*as-heading:2(快速入門:在PDF中替換文字)*
新增IronPDF依賴,載入或渲染PDF,調用`replaceText`,並保存結果:
```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("<h1>.NET6</h1>");
pdf.replaceText(PageSelection.firstPage(), ".NET6", ".NET7");
pdf.saveAs("replaceText.pdf");
}
}
```
<div class="hsg-featured-snippet">
<h3>最小工作流程(5步驟)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="download-modal" href="#download-modal">下載Java庫以在PDF中替換文字</a></li>
<li>載入現有的PDF或從HTML渲染一個PDF</li>
<li>調用<code>pdf.replaceText(PageSelection, oldText, newText)</code>以在目標頁上替換</li>
<li>使用<code>PageSelection</code>方法來控制修改頁面</li>
<li>使用<code>pdf.saveAs("output.pdf")</code>保存和導出已更新的PDF</li>
</ol>
</div>
## 如何在單頁上替換文字?
`PageSelection`用於定位一個或多個頁面,精確要查找的文字,以及替換字串。 要定位到第一頁,傳遞`PageSelection.firstPage()`。 在該頁面的所有搜索字串實例在一次調用中被替換。 如果在目標頁面上找不到文字,則該方法會拋出運行時異常。 下面的截圖顯示了控制台中該異常的樣子。

### replaceText接受哪些參數?
方法簽名是`replaceText(PageSelection pageSelection, String oldText, String newText)`。 預設情況下匹配是區分大小寫的:`"NET6"`被視為不同的字串。 在調用該方法之前,請驗證已渲染PDF中的精確大小寫。 您可以先[提取PDF的文字內容](https://ironpdf.com/java/examples/extract-image-from-pdf/)來確認精確的文字。IronPDF Java依賴已發布在[Maven Central](https://central.sonatype.com/artifact/com.ironsoftware/ironpdf)上,並需要Java 8或更高版本。
```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");
}
}
```
[[t:(在應用程式啟動時載入一次授權金鑰,不要在每個單獨操作之前載入。 這樣可以避免在同一JVM會話中處理多個文件時重複初始化的開銷。)]]
`replaceText`方法與IronPDF的[HTML到PDF轉換工作流](https://ironpdf.com/java/tutorials/html-to-pdf/)自然整合。 首先渲染HTML模板,然後應用文字替換以注入動態值。 這樣可以保持HTML清潔,同時產出個性化輸出。 對於從磁碟載入的文件,請將檔案路徑傳遞給`renderHtmlAsPdf`。
### 輸出看起來如何?
<iframe loading="lazy" src="/static-assets/ironpdf-java/howto/find-replace-text/replaceText.pdf" width="100%" height="400px"></iframe>
<hr />
## 如何在多個頁面上替換文字?
要定位特定的頁面而不是僅僅是第一頁,請傳遞零為基的頁碼列表到`PageSelection.pageRange(List<Integer>)`。 該方法替換列表中每個頁面的搜索文字,並保持所有其他頁面不變。 這種模式適合已知頁面上具有一致標題或頁腳的文件,或在某些頁面中才會出現版本字串的批量生成報告。
### 使用頁面列表時會修改哪些頁面?
在下面的例子中,從HTML建立了一個三頁的PDF。 替換在頁面`2`(第一和第三頁)上運行。 頁面`1`(第二頁)保持原文不變。 頁面索引總是從`0`開始,與Java的零基數陣列約定一致。
```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");
}
}
```
[[i:(在IronPDF中,所有頁面索引都遵循零基數索引。 頁面`1`是第二頁,依此類推。)]]
在從HTML建立多頁PDF時,使用[CSS `page-break-after` 屬性](https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-after)來控制頁面邊界的位置。 在渲染前設置合適的[自定義紙張尺寸](https://ironpdf.com/java/examples/custom-pdf-paper-size/)和[頁面方向](https://ironpdf.com/java/examples/pdf-page-orientation/)可確保在執行文字替換時內容位置符合您的預期。 保存後,打開PDF並確認只有目標頁面發生了變化來驗證輸出。
### 輸出看起來如何?
<iframe loading="lazy" src="/static-assets/ironpdf-java/howto/find-replace-text/replaceTextOnMultiplePages.pdf" width="100%" height="400px"></iframe>
<hr />
## 有哪些頁面選擇選項可用?
`PageSelection`類提供靜態工廠方法,涵蓋每個常見的目標模式。 不需要建立實例; 直接在類上調用方法。 所有索引都是零基數。
### 哪些方法針對單頁與多頁?
<table class="content__data-table" data-content-table>
<caption>replaceText API的PageSelection工廠方法</caption>
|方法|描述|
|---|---|
| `PageSelection.allPages()` |選擇文件中的每一頁|
| `PageSelection.firstPage()` |選擇索引`0`處的頁面|
| `PageSelection.lastPage()` |不論文件長度選擇最後一頁|
| `PageSelection.singlePage(int pageIndex)` |按零基數索引選擇一個特定頁面|
| `PageSelection.pageRange(int startIndex, int endIndex)` |選擇從`endIndex`的連續範圍,包含起止頁|
| `PageSelection.pageRange(List<Integer> pageList)` |選擇任意索引集上的頁面(例如,`[0, 2]`選擇頁面1和3)|
</table>
### 什麼時候應該使用每個PageSelection方法?
`allPages()`是全域查找和替換的最簡選擇:整個文件中目標文字的每個實例都在一次調用中被替換。 使用`lastPage()`進行快速編輯,以覆蓋頁面或最後頁頁腳而不觸碰主體。 當文字出現在一系列連續頁面如章節或段落時選擇`pageRange(int, int)`。 當目標頁面是不連續的時使用`pageRange(List<Integer>)`; 例如,當替換僅在第1頁、第3頁和第7頁出現的版本字串時。
處理[合併的PDF](https://ironpdf.com/java/examples/split-pdfs/)或包含[書籤和大綱](https://ironpdf.com/java/how-to/bookmarks/)的文件時,首先識別每個邏輯部分的頁面範圍,然後應用目標替換以避免意外修改共享的標題或頁腳。 [IronPDF for Java API參考](https://ironpdf.com/object-reference/api/)列出所有`PageSelection`重載,並附有完整的參數說明。
[[n:(將`replaceText`調用包裹於try-catch塊中。 當指定的搜索文字未在任何目標頁面上找到時,該方法會拋出運行時異常。 驗證步驟(提取文字並確認字串存在)可防止在生產中出現意外失敗。)]]
### 如何一次替換所有頁面的文字?
`PageSelection.allPages()`在一次調用中執行整個文件的替換,這是全球標記替換的最有效方法。 下面的例子從磁碟載入一個PDF,並替換整個文件中每次出現的占位符標記:
```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");
}
}
```
這種模式自然地與模板驅動的工作流搭配使用,其中相同的占位符在許多頁面上的標題、頁腳或正文中出現。 對於單頁文件,`firstPage()`生成相同的結果。 在頁面數可能在運行時變化時偏好`allPages()`。
<hr />
## 如何處理常見的文字替換情境?
Java應用程式中的文字替換涵蓋的多個模式超越了簡單的查找替換。 了解該方法在每種情況下的行為可防止在生產中出現漏洞。
### 大小寫敏感匹配如何影響結果?
`replaceText`執行精確的、區分大小寫的匹配。 字串`"VERSION 1.0"`被視為三個不同的值。 在對從磁碟載入的文件運行替換之前,通過查看原始來源或[從PDF提取文字](https://ironpdf.com/java/examples/extract-image-from-pdf/)並以程式方式檢查來確認精確大小寫。
### 如何在PDF表單中替換文字?
包含互動表單欄位的PDF根據[PDF規範](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)將其文字值儲存在文件的內容流之外。 `replaceText`方法在內容流上運行,並不修改表單欄位值。 要更新表單欄位內的文字,請改用IronPDF的專用[表單建立和編輯API](https://ironpdf.com/java/how-to/create-forms/)。 在同一文件中混合使用這兩種方法是安全的:表單欄位更新和內容流替換不會相互干擾。
### 如何在基於模板的工作流中更新文字?
常見模式是維護含有占位符標記的PDF模板(例如`[INVOICE_DATE]`),並在運行時用實際值替換它們。 為每個占位符調用`PageSelection.allPages()`以便替換包括標記出現的每個位置。 對於從HTML生成的文件,這種工作流使用`renderHtmlAsPdf`,然後再進行一系列替換調用,一樣有效。 將此與[PDF浮水印](https://ironpdf.com/java/how-to/custom-watermark/)或[背景和前景](https://ironpdf.com/java/how-to/background-foreground/)結合使用,以在最終輸出中新增品牌或保密標記。
## PDF文字替換在Java中的下一步是什麼?
本指南涵蓋了使用`PageSelection`工廠方法。 無論文件是從HTML渲染的,從磁碟載入的,還是通過合併多個來源組裝的,這個`replaceText` API都可以使用。
[開始IronPDF for Java的免費試用](#trial-license),並將上面的程式碼範例運行在您自己的文件上。 當您準備好部署生產時,[查看授權選項](#licensing)。 授權按開發者計算,並包含一年產品更新。
準備好看看IronPDF for Java還可以做什麼嗎? 瀏覽完整的[IronPDF for Java操作指南](https://ironpdf.com/java/),獲取有關PDF生成、註解、[數位簽名](https://ironpdf.com/java/examples/pdf-signatures/)、[壓縮](https://ironpdf.com/java/examples/pdf-compression/)等的教程。
Ask ChatGPT about this page
Ask Gemini about this page
Ask Perplexity about this page
IronPDF for Java讓開發者通過replaceText方法直接控制現有的PDF內容。 無論您需要在一批生成的報告中更正拼寫錯誤、更換模板文件中的版本號,還是用客戶特定資料來個性化合同,該方法接受頁面選擇、搜索字串和替換字串,並處理其餘的工作。本指南涵蓋了單頁替換、多頁目標、每個可用的PageSelection選項以及適用於模板驅動工作流的實用模式。
新增IronPDF依賴,載入或渲染PDF,調用replaceText,並保存結果:
1 Install IronPDF with Maven Central Repository
> mvn install
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2026.6.1</version>
</dependency>
2 複製並運行這段程式碼片段。
//: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( "<h1>.NET6</h1>" );
pdf.replaceText( PageSelection .firstPage(), ".NET6" , ".NET7" );
pdf.saveAs( "replaceText.pdf" );
}
}
//: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("<h1>.NET6</h1>");
pdf.replaceText(PageSelection.firstPage(), ".NET6", ".NET7");
pdf.saveAs("replaceText.pdf");
}
}
Java
3 部署以在您的實時環境中測試
今天就開始在您的專案中使用IronPDF,透過免費試用
免費30天試用
最小工作流程(5步驟) 下載Java庫以在PDF中替換文字 載入現有的PDF或從HTML渲染一個PDF 調用pdf.replaceText(PageSelection, oldText, newText)以在目標頁上替換 使用PageSelection方法來控制修改頁面 使用pdf.saveAs("output.pdf")保存和導出已更新的PDF
如何在單頁上替換文字?
PageSelection用於定位一個或多個頁面,精確要查找的文字,以及替換字串。 要定位到第一頁,傳遞PageSelection.firstPage()。 在該頁面的所有搜索字串實例在一次調用中被替換。 如果在目標頁面上找不到文字,則該方法會拋出運行時異常。 下面的截圖顯示了控制台中該異常的樣子。
replaceText接受哪些參數?
方法簽名是replaceText(PageSelection pageSelection, String oldText, String newText)。 預設情況下匹配是區分大小寫的:"NET6"被視為不同的字串。 在調用該方法之前,請驗證已渲染PDF中的精確大小寫。 您可以先提取PDF的文字內容 來確認精確的文字。IronPDF Java依賴已發布在Maven Central 上,並需要Java 8或更高版本。
1 Install IronPDF with Maven Central Repository
> mvn install
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2026.6.1</version>
</dependency>
2 複製並運行這段程式碼片段。
//: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" );
}
}
//: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");
}
}
Java
3 部署以在您的實時環境中測試
今天就開始在您的專案中使用IronPDF,透過免費試用
免費30天試用
在應用程式啟動時載入一次授權金鑰,不要在每個單獨操作之前載入。 這樣可以避免在同一JVM會話中處理多個文件時重複初始化的開銷。
replaceText方法與IronPDF的HTML到PDF轉換工作流 自然整合。 首先渲染HTML模板,然後應用文字替換以注入動態值。 這樣可以保持HTML清潔,同時產出個性化輸出。 對於從磁碟載入的文件,請將檔案路徑傳遞給renderHtmlAsPdf。
輸出看起來如何?
如何在多個頁面上替換文字?
要定位特定的頁面而不是僅僅是第一頁,請傳遞零為基的頁碼列表到PageSelection.pageRange(List<Integer>)。 該方法替換列表中每個頁面的搜索文字,並保持所有其他頁面不變。 這種模式適合已知頁面上具有一致標題或頁腳的文件,或在某些頁面中才會出現版本字串的批量生成報告。
使用頁面列表時會修改哪些頁面?
在下面的例子中,從HTML建立了一個三頁的PDF。 替換在頁面2(第一和第三頁)上運行。 頁面1(第二頁)保持原文不變。 頁面索引總是從0開始,與Java的零基數陣列約定一致。
1 Install IronPDF with Maven Central Repository
> mvn install
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2026.6.1</version>
</dependency>
2 複製並運行這段程式碼片段。
//: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" );
}
}
//: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");
}
}
Java
3 部署以在您的實時環境中測試
今天就開始在您的專案中使用IronPDF,透過免費試用
免費30天試用
在IronPDF中,所有頁面索引都遵循零基數索引。 頁面1是第二頁,依此類推。
在從HTML建立多頁PDF時,使用CSS page-break-after 屬性 來控制頁面邊界的位置。 在渲染前設置合適的自定義紙張尺寸 和頁面方向 可確保在執行文字替換時內容位置符合您的預期。 保存後,打開PDF並確認只有目標頁面發生了變化來驗證輸出。
輸出看起來如何?
有哪些頁面選擇選項可用?
PageSelection類提供靜態工廠方法,涵蓋每個常見的目標模式。 不需要建立實例; 直接在類上調用方法。 所有索引都是零基數。
哪些方法針對單頁與多頁?
什麼時候應該使用每個PageSelection方法?
allPages()是全域查找和替換的最簡選擇:整個文件中目標文字的每個實例都在一次調用中被替換。 使用lastPage()進行快速編輯,以覆蓋頁面或最後頁頁腳而不觸碰主體。 當文字出現在一系列連續頁面如章節或段落時選擇pageRange(int, int)。 當目標頁面是不連續的時使用pageRange(List<Integer>); 例如,當替換僅在第1頁、第3頁和第7頁出現的版本字串時。
處理合併的PDF 或包含書籤和大綱 的文件時,首先識別每個邏輯部分的頁面範圍,然後應用目標替換以避免意外修改共享的標題或頁腳。 IronPDF for Java API參考 列出所有PageSelection重載,並附有完整的參數說明。
將replaceText調用包裹於try-catch塊中。 當指定的搜索文字未在任何目標頁面上找到時,該方法會拋出運行時異常。 驗證步驟(提取文字並確認字串存在)可防止在生產中出現意外失敗。
如何一次替換所有頁面的文字?
PageSelection.allPages()在一次調用中執行整個文件的替換,這是全球標記替換的最有效方法。 下面的例子從磁碟載入一個PDF,並替換整個文件中每次出現的占位符標記:
1 Install IronPDF with Maven Central Repository
> mvn install
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2026.6.1</version>
</dependency>
2 複製並運行這段程式碼片段。
//: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" );
}
}
//: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");
}
}
Java
3 部署以在您的實時環境中測試
今天就開始在您的專案中使用IronPDF,透過免費試用
免費30天試用
這種模式自然地與模板驅動的工作流搭配使用,其中相同的占位符在許多頁面上的標題、頁腳或正文中出現。 對於單頁文件,firstPage()生成相同的結果。 在頁面數可能在運行時變化時偏好allPages()。
如何處理常見的文字替換情境?
Java應用程式中的文字替換涵蓋的多個模式超越了簡單的查找替換。 了解該方法在每種情況下的行為可防止在生產中出現漏洞。
大小寫敏感匹配如何影響結果?
replaceText執行精確的、區分大小寫的匹配。 字串"VERSION 1.0"被視為三個不同的值。 在對從磁碟載入的文件運行替換之前,通過查看原始來源或從PDF提取文字 並以程式方式檢查來確認精確大小寫。
如何在PDF表單中替換文字?
包含互動表單欄位的PDF根據PDF規範 將其文字值儲存在文件的內容流之外。 replaceText方法在內容流上運行,並不修改表單欄位值。 要更新表單欄位內的文字,請改用IronPDF的專用表單建立和編輯API 。 在同一文件中混合使用這兩種方法是安全的:表單欄位更新和內容流替換不會相互干擾。
如何在基於模板的工作流中更新文字?
常見模式是維護含有占位符標記的PDF模板(例如[INVOICE_DATE]),並在運行時用實際值替換它們。 為每個占位符調用PageSelection.allPages()以便替換包括標記出現的每個位置。 對於從HTML生成的文件,這種工作流使用renderHtmlAsPdf,然後再進行一系列替換調用,一樣有效。 將此與PDF浮水印 或背景和前景 結合使用,以在最終輸出中新增品牌或保密標記。
PDF文字替換在Java中的下一步是什麼?
本指南涵蓋了使用PageSelection工廠方法。 無論文件是從HTML渲染的,從磁碟載入的,還是通過合併多個來源組裝的,這個replaceText API都可以使用。
開始IronPDF for Java的免費試用 ,並將上面的程式碼範例運行在您自己的文件上。 當您準備好部署生產時,查看授權選項 。 授權按開發者計算,並包含一年產品更新。
準備好看看IronPDF for Java還可以做什麼嗎? 瀏覽完整的IronPDF for Java操作指南 ,獲取有關PDF生成、註解、數位簽名 、壓縮 等的教程。
常見問題 使用IronPDF的replaceText方法。呼叫pdf.replaceText(PageSelection.firstPage(), "oldText", "newText")以替換指定頁面上舊文字的所有實例。IronPDF在保持原始格式的同時找到並替換每個出現的地方。
該方法接受三個參數:一個PageSelection指定要修改的頁面,一個包含要查找文字的String,以及一個包含替換文字的String。例如,pdf.replaceText(PageSelection.firstPage(), ".NET6", ".NET7")替換第一頁上所有的實例。
可以。使用PageSelection.firstPage()表示第0頁,PageSelection.lastPage()表示最後一頁,PageSelection.singlePage(n)用於任何頁面以零為基索引,或使用PageSelection.pageRange()與整數列表表示不連續頁面。
當無法在目標頁面找到目標文字時,IronPDF會拋出運行時異常(Exception_RemoteException)。將呼叫包裝在try-catch區塊中,並在呼叫replaceText之前選擇性提取PDF文字以驗證字串存在。
是。replaceText方法執行精確的區分大小寫匹配。字串"Version 1.0"、"version 1.0" 和 "VERSION 1.0"被視為三個不同的值。在呼叫該方法前核對精確的大小寫。
不。replaceText方法操作於PDF內容流,不會修改互動表單欄位值。要更新表單字段,請使用IronPDF的專用表單編輯API通過PdfDocument表單方法。
使用PageSelection.allPages()作為replaceText方法的第一個參數。這在單次呼叫中替換目標文字在所有頁面的每一個實例,是文件寬占位符模板驅動工作流程的首選方法。
IronPDF's `replaceText` method operates on content streams and does not affect form field values. For form field modification, use IronPDF's form creation and editing API.
Maintain a PDF template with placeholders like `{{CUSTOMER_NAME}}`. Use `replaceText` with `PageSelection.allPages()` to substitute these placeholders with actual values at runtime.
Start by downloading a free trial of IronPDF for Java. Follow the documentation and code examples to replace text in PDFs. Consider licensing options when you're ready for production deployment.
技術作家
Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。
...
閱讀更多