如何在PDF中替換文字

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

IronPDF for Java讓開發者通過replaceText方法直接控制現有的PDF內容。 無論您需要在一批生成的報告中更正拼寫錯誤、更換模板文件中的版本號,還是用客戶特定資料來個性化合同,該方法接受頁面選擇、搜索字串和替換字串,並處理其餘的工作。本指南涵蓋了單頁替換、多頁目標、每個可用的PageSelection選項以及適用於模板驅動工作流的實用模式。

快速入門:在PDF中替換文字

新增IronPDF依賴,載入或渲染PDF,調用replaceText,並保存結果:

 :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");
    }
}
 :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");
    }
}
JAVA

如何在單頁上替換文字?

PageSelection用於定位一個或多個頁面,精確要查找的文字,以及替換字串。 要定位到第一頁,傳遞PageSelection.firstPage()。 在該頁面的所有搜索字串實例在一次調用中被替換。 如果在目標頁面上找不到文字,則該方法會拋出運行時異常。 下面的截圖顯示了控制台中該異常的樣子。

IronPDF控制台輸出顯示當目標文字'.NET7'在replaceText中未找到時的Exception_RemoteException

replaceText接受哪些參數?

方法簽名是replaceText(PageSelection pageSelection, String oldText, String newText)。 預設情況下匹配是區分大小寫的:"NET6"被視為不同的字串。 在調用該方法之前,請驗證已渲染PDF中的精確大小寫。 您可以先提取PDF的文字內容來確認精確的文字。IronPDF Java依賴已發布在Maven Central上,並需要Java 8或更高版本。

 :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");
    }
}
 :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");
    }
}
JAVA

提示在應用程式啟動時載入一次授權金鑰,不要在每個單獨操作之前載入。 這樣可以避免在同一JVM會話中處理多個文件時重複初始化的開銷。

replaceText方法與IronPDF的HTML到PDF轉換工作流自然整合。 首先渲染HTML模板,然後應用文字替換以注入動態值。 這樣可以保持HTML清潔,同時產出個性化輸出。 對於從磁碟載入的文件,請將檔案路徑傳遞給renderHtmlAsPdf

輸出看起來如何?


如何在多個頁面上替換文字?

要定位特定的頁面而不是僅僅是第一頁,請傳遞零為基的頁碼列表到PageSelection.pageRange(List<Integer>)。 該方法替換列表中每個頁面的搜索文字,並保持所有其他頁面不變。 這種模式適合已知頁面上具有一致標題或頁腳的文件,或在某些頁面中才會出現版本字串的批量生成報告。

使用頁面列表時會修改哪些頁面?

在下面的例子中,從HTML建立了一個三頁的PDF。 替換在頁面2(第一和第三頁)上運行。 頁面1(第二頁)保持原文不變。 頁面索引總是從0開始,與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");
    }
}
 :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");
    }
}
JAVA

請注意在IronPDF中,所有頁面索引都遵循零基數索引。 頁面1是第二頁,依此類推。

在從HTML建立多頁PDF時,使用CSS page-break-after 屬性來控制頁面邊界的位置。 在渲染前設置合適的自定義紙張尺寸頁面方向可確保在執行文字替換時內容位置符合您的預期。 保存後,打開PDF並確認只有目標頁面發生了變化來驗證輸出。

輸出看起來如何?


Icon Quote related to 輸出看起來如何?

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 輸出看起來如何?

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 輸出看起來如何?

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 輸出看起來如何?

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 輸出看起來如何?

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 輸出看起來如何?

David Jones

首席軟體工程師,Agorus Build

查看案例研究

有哪些頁面選擇選項可用?

PageSelection類提供靜態工廠方法,涵蓋每個常見的目標模式。 不需要建立實例; 直接在類上調用方法。 所有索引都是零基數。

哪些方法針對單頁與多頁?

|方法|描述| |---|---| | `PageSelection.allPages()` |選擇文件中的每一頁| | `PageSelection.firstPage()` |選擇索引`0`處的頁面| | `PageSelection.lastPage()` |不論文件長度選擇最後一頁| | `PageSelection.singlePage(int pageIndex)` |按零基數索引選擇一個特定頁面| | `PageSelection.pageRange(int startIndex, int endIndex)` |選擇從`endIndex`的連續範圍,包含起止頁| | `PageSelection.pageRange(List pageList)` |選擇任意索引集上的頁面(例如,`[0, 2]`選擇頁面1和3)|
replaceText API的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,並替換整個文件中每次出現的占位符標記:

 :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");
    }
}
 :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");
    }
}
JAVA

這種模式自然地與模板驅動的工作流搭配使用,其中相同的占位符在許多頁面上的標題、頁腳或正文中出現。 對於單頁文件,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生成、註解、數位簽名壓縮等的教程。

常見問題

如何使用Java在PDF中替換文字?

使用IronPDF的replaceText方法。呼叫pdf.replaceText(PageSelection.firstPage(), "oldText", "newText")以替換指定頁面上舊文字的所有實例。IronPDF在保持原始格式的同時找到並替換每個出現的地方。

replaceText方法接受哪些參數?

該方法接受三個參數:一個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會修改表單字段值嗎?

不。replaceText方法操作於PDF內容流,不會修改互動表單欄位值。要更新表單字段,請使用IronPDF的專用表單編輯API通過PdfDocument表單方法。

如何一次在每一頁上替換一個token?

使用PageSelection.allPages()作為replaceText方法的第一個參數。這在單次呼叫中替換目標文字在所有頁面的每一個實例,是文件寬占位符模板驅動工作流程的首選方法。

Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant擁有邁阿密大學的電腦科學學士學位,並在Iron Software擔任全端WebOps行銷工程師。從小就對程式設計有興趣,他認為計算既神秘又易於理解,成為創意和問題解決的完美媒介。

在Iron Software,Darrius喜歡創造新事物並簡化複雜的概念,使其更易於理解。作為我們的常駐開發人員之一,他還志願教學,將他的專業知識傳授給下一代。

對Darrius來說,他的工作是有意義的,因為它有價值且對社會有真正的影響。

準備好開始了嗎?
版本: 2026.6 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想要快速證明嗎?
運行範例 觀看您的HTML變成PDF。