如何在 Java 中刪除 PDF 中的頁面

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

使用 IronPDF for Java 在 Java 中移除 PDF 頁面非常簡單:該函式庫提供了由 PageSelection 支援的 removePageremovePages 方法,讓您能精確控制要刪除的頁面——無論是單一頁面、連續範圍,還是分散的頁面索引集。 IronPDF 中的所有頁面索引均以 0 為起點,因此文件的第一頁索引始終為 0。

快速入門:在 Java 中刪除 PDF 頁面

  1. 透過 Maven 或 Gradle 安裝 IronPDF for Java
  2. 使用 License.setLicenseKey() 設定您的授權金鑰
  3. 載入 PDF 檔案 PdfDocument.fromFile()
  4. 移除單一頁面 removePage()
  5. 將結果儲存為 saveAs()

```java :title=快速入門 //:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/quickstart.java import java.io.IOException; import java.nio.file.Path; import com.ironsoftware.IronPdf.License; import com.ironsoftware.IronPdf.PdfDocument;

public class Main { public static void main(String[] args) throws IOException { // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰 License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

    // 從磁碟載入原始 PDF
    PdfDocument pdf = PdfDocument.fromFile(Path.of("source.pdf"));

    // 移除第一頁(從 0 開始計數)
    pdf.removePage(0);

    // 將修改後的 PDF 儲存至新檔案
    pdf.saveAs(Path.of("modified.pdf"));
}

}


從 PDF 中移除頁面是一項常見的文件處理任務。 您可能需要在分發報告前移除封面頁、在對外分享文件前刪除機密段落,或是清理掃描器或範本產生的空白頁面。 IronPDF 透過一致的 Java API 處理所有這些情況,無需在主機上安裝任何原生 PDF 編輯工具。

此函式庫可透過 Maven 或 Gradle 整合至 Java 應用程式中,並支援除刪除頁面以外的完整 PDF 處理操作,包括[合併 PDF](https://ironpdf.com/java/how-to/java-merge-pdf-tutorial/)、[分割文件](https://ironpdf.com/java/how-to/java-split-pdf-tutorial/)以及[添加浮水印](https://ironpdf.com/java/how-to/custom-watermark/)。 如需了解完整的設定指南及可用功能,請參閱《[入門指南](https://ironpdf.com/java/docs/)》。

本指南中的範例涵蓋三種情境:透過索引刪除單一頁面、使用 `PageSelection` 刪除連續的頁面範圍,以及在不觸發索引偏移錯誤的情況下,安全地刪除多個非連續頁面。

<div class="hsg-featured-snippet">
    <h2>如何在 Java 中刪除 PDF 中的頁面</h2>
    <ol>
        <li><a href="https://ironpdf.com/java/#download-modal">安裝 Java 函式庫以刪除 PDF 頁面</a></li>
        <li>使用 <strong>PdfDocument</strong> 類別載入 PDF</li>
        <li>使用 <code>removePage</code> 根據索引刪除單一頁面</li>
        <li>搭配 <code>PageSelection</code> 使用 <code>removePages</code> 來刪除多頁或範圍內的頁面</li>
        <li>使用 <code>saveAs 功能</code>儲存修改後的 PDF</li>
    </ol>
</div>

## 開始之前需要準備什麼?

在從 PDF 中移除頁面之前,請確認您的 Java 專案中已設定 IronPDF。 此函式庫需使用 Java 8 或更高版本,並可透過 [Maven 或 Gradle](https://central.sonatype.com/artifact/com.ironsoftware/ironpdf) 進行整合。 請將 `IronPdf` 依賴項新增至您的專案建置檔案。完整的設定說明請參閱《[入門概覽](https://ironpdf.com/java/docs/)》。

無論是開發或生產環境,均需使用有效的授權金鑰。 請在呼叫任何 IronPDF 方法之前,於應用程式開頭設定金鑰。 有關授權選項的詳細資訊,請參閱[授權金鑰指南](https://ironpdf.com/java/get-started/license-keys/)。

提示IronPDF 中的所有頁面索引均採用從零開始的編號。 (您的文件第 1 頁對應索引 0,第 2 頁對應索引 1,依此類推。
## 如何從 PDF 中刪除單一頁面? `removePage(int pageIndex)` 方法接受以零為起點的頁面索引,並從文件中精確移除該頁面。 呼叫完成後,後續所有頁面都會向下移動一個位置,因此您在呼叫前快取的任何索引可能不再指向同一頁面。 例如,若文件共有五頁(索引 0 至 4),當您移除索引 2 時,原先位於索引 3 的頁面將移至索引 2,而原本位於索引 4 的頁面則移至索引 3。請在規劃移除順序時留意此變動,特別是在連續多次呼叫 `removePage` 時。 ```java //:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/single-page.java import java.io.IOException; import java.nio.file.Path; import com.ironsoftware.IronPdf.License; import com.ironsoftware.IronPdf.PdfDocument; public class Main { public static void main(String[] args) throws IOException { // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰 License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01"); // 從磁碟載入原始 PDF PdfDocument pdf = PdfDocument.fromFile(Path.of("report.pdf")); // Remove the cover page at index 0 (the first page) pdf.removePage(0); // Save the modified PDF -- the original file is not overwritten pdf.saveAs(Path.of("report-no-cover.pdf")); } }

當您確切知道要移除哪個頁面,且僅需移除一個頁面時,此模式是最簡單的方法。 若要透過單一操作移除連續的頁面範圍,請改為使用 removePages 並搭配 PageSelection 範圍。

如何從 PDF/A 中刪除一組頁面?

removePages(PageSelection) 方法會透過單一原子操作刪除選取範圍內的所有頁面,藉此避免因多次呼叫 removePage 而產生的索引位移問題。 請使用 PageSelection.pageRange(int fromIndex, int toIndex) 來指定範圍——兩端點均包含在內,且以零為起點。

以下範例透過傳遞 fromIndex = 2toIndex = 4,移除文件的第 3、4 和 5 頁。 由於這三個頁面是同時移除的,因此操作過程中不會發生中間索引位移。

//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/page-range.java
import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.IronPdf.License;
import com.ironsoftware.IronPdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;

public class Main {
    public static void main(String[] args) throws IOException {
        // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰
        License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

        // Load a multi-page PDF from disk
        PdfDocument pdf = PdfDocument.fromFile(Path.of("annual-report.pdf"));

        // Remove pages 3, 4, and 5 using a zero-based inclusive range (indexes 2 to 4)
        pdf.removePages(PageSelection.pageRange(2, 4));

        // Save the result to a new file
        pdf.saveAs(Path.of("annual-report-trimmed.pdf"));
    }
}
//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/page-range.java
import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.IronPdf.License;
import com.ironsoftware.IronPdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;

public class Main {
    public static void main(String[] args) throws IOException {
        // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰
        License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

        // Load a multi-page PDF from disk
        PdfDocument pdf = PdfDocument.fromFile(Path.of("annual-report.pdf"));

        // Remove pages 3, 4, and 5 using a zero-based inclusive range (indexes 2 to 4)
        pdf.removePages(PageSelection.pageRange(2, 4));

        // Save the result to a new file
        pdf.saveAs(Path.of("annual-report-trimmed.pdf"));
    }
}
JAVA

PageSelection.pageRange 是您需要移除一整段相鄰頁面時的首選方法。 這比逐一循環處理 removePage 呼叫更簡潔高效,且單一操作的語意意味著頁數僅會更新一次。

如何刪除多個非連續的頁面?

當您需要移除非相鄰的頁面時,有兩種實用的選項:使用 removePages 搭配針對個別索引的 PageSelection,或以精心排序的順序多次呼叫 removePage

若多次呼叫 removePage,請務必從最高索引開始依序處理至最低索引。若先移除索引較低的頁面,會導致所有較高索引的頁面向下Shift一位,進而使後續的呼叫指向錯誤的頁面。 透過從文件末端開始並向後處理,每次移除操作都不會影響剩餘的較低索引。

以下範例將從一份六頁的文件中移除第一頁、中間的一頁以及最後一頁。 呼叫順序依索引值由高至低排列——5、3、0——以防止索引漂移。

//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/non-consecutive-pages.java
import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.IronPdf.License;
import com.ironsoftware.IronPdf.PdfDocument;

public class Main {
    public static void main(String[] args) throws IOException {
        // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰
        License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

        // Load a six-page PDF from disk
        PdfDocument pdf = PdfDocument.fromFile(Path.of("contract.pdf"));

        // Remove non-consecutive pages: always work from highest index to lowest
        // to prevent index shifting from affecting subsequent removals.

        // Remove the last page (index 5 in a six-page document)
        pdf.removePage(5);

        // Remove a page in the middle (index 3 -- now safe because no lower index has shifted)
        pdf.removePage(3);

        // Remove the first page (index 0 -- lowest, so processed last)
        pdf.removePage(0);

        // Save the modified PDF
        pdf.saveAs(Path.of("contract-redacted.pdf"));
    }
}
//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/non-consecutive-pages.java
import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.IronPdf.License;
import com.ironsoftware.IronPdf.PdfDocument;

public class Main {
    public static void main(String[] args) throws IOException {
        // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰
        License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

        // Load a six-page PDF from disk
        PdfDocument pdf = PdfDocument.fromFile(Path.of("contract.pdf"));

        // Remove non-consecutive pages: always work from highest index to lowest
        // to prevent index shifting from affecting subsequent removals.

        // Remove the last page (index 5 in a six-page document)
        pdf.removePage(5);

        // Remove a page in the middle (index 3 -- now safe because no lower index has shifted)
        pdf.removePage(3);

        // Remove the first page (index 0 -- lowest, so processed last)
        pdf.removePage(0);

        // Save the modified PDF
        pdf.saveAs(Path.of("contract-redacted.pdf"));
    }
}
JAVA

請注意在建立要於執行時移除的頁面索引清單時——例如根據使用者輸入或設定檔——請在迭代前將清單依降序排列。 這可確保每個 removePage 呼叫都能指向正確的頁面,無論先前已被移除多少頁面。)}]

若需移除的頁面集是動態決定的,一種簡潔的處理方式是將索引清單倒序排序,然後進行迴圈處理:

//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/dynamic-removal.java
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import com.ironsoftware.IronPdf.License;
import com.ironsoftware.IronPdf.PdfDocument;

public class Main {
    public static void main(String[] args) throws IOException {
        // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰
        License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

        // Load the PDF from disk
        PdfDocument pdf = PdfDocument.fromFile(Path.of("document.pdf"));

        // Define the zero-based page indexes to remove
        List<Integer> pagesToRemove = Arrays.asList(0, 3, 5);

        // Sort descending to avoid index-shift errors during sequential removal
        pagesToRemove.sort(Comparator.reverseOrder());

        // Remove each page in reverse-index order
        for (int pageIndex : pagesToRemove) {
            pdf.removePage(pageIndex);
        }

        // Save the modified PDF
        pdf.saveAs(Path.of("document-pages-removed.pdf"));
    }
}
//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/dynamic-removal.java
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import com.ironsoftware.IronPdf.License;
import com.ironsoftware.IronPdf.PdfDocument;

public class Main {
    public static void main(String[] args) throws IOException {
        // 在呼叫任何 IronPDF 方法之前,請先設定授權金鑰
        License.setLicenseKey("IronPDF-MYLICENSE-KEY-1EF01");

        // Load the PDF from disk
        PdfDocument pdf = PdfDocument.fromFile(Path.of("document.pdf"));

        // Define the zero-based page indexes to remove
        List<Integer> pagesToRemove = Arrays.asList(0, 3, 5);

        // Sort descending to avoid index-shift errors during sequential removal
        pagesToRemove.sort(Comparator.reverseOrder());

        // Remove each page in reverse-index order
        for (int pageIndex : pagesToRemove) {
            pdf.removePage(pageIndex);
        }

        // Save the modified PDF
        pdf.saveAs(Path.of("document-pages-removed.pdf"));
    }
}
JAVA

在迴圈執行前將索引清單依降序排序,是一種安全且通用的模式,無論目標頁面數量為何,或輸入清單的排序方式為何,此模式皆能有效運作。

在 Java 中刪除 PDF 頁面的下一步該怎麼做?

IronPDF 的 removePageremovePages 方法可讓您精準控制頁面刪除操作——無論您需要刪除單一頁面、移除特定範圍,還是刪除零散的頁面集合。 IronPDF Java API 全面採用零基索引模型,因此當您進行頁面分割、合併或重新排序時,同樣的規範亦適用。

若要繼續探索 PDF 頁面結構與文件處理相關內容,請參閱以下相關資源:

立即開始免費試用,在您的 Java 工作流程中移除 PDF 文件中的頁面。 如需購買用於生產環境的授權,請查看授權選項

常見問題

如何在 Java 中刪除 PDF 中的單一頁面?

使用 PdfDocument.fromFile() 載入 PDF 檔案,接著以零起始索引呼叫 pdf.removePage(pageIndex)。例如,pdf.removePage(0) 將移除第一頁。最後使用 pdf.saveAs() 儲存結果。

如何在 Java 中從 PDF 中移除一組頁面?

呼叫 pdf.removePages(PageSelection.pageRange(fromIndex, toIndex))。from 和 to 索引均以零為起點且包含起始索引。例如,PageSelection.pageRange(2, 4) 將透過單一原子操作移除文件中的第三、第四及第五頁。

為什麼我需要將頁面從索引最高到最低的順序中移除?

當您多次呼叫 removePage 時,每次移除操作都會將後續所有頁面索引向下推移一個位置。從最高索引開始依序移除,可確保每次呼叫都能鎖定正確的頁面,因為此時尚未移除任何索引較低的頁面,因此不會造成索引位移。

IronPDF for Java 中的 PageSelection 是什麼?

PageSelectioncom.ironsoftware.ironpdf.edit 套件中的類別,用於定義方法應作用於哪些頁面。PageSelection.pageRange(fromIndex, toIndex) 會建立一個選取範圍,涵蓋以零為起點且包含起始與結束頁碼的連續頁面區塊,供 removePages 方法使用。

在 Java 中使用 IronPDF 刪除 PDF 頁面的先決條件是什麼?

您需要 Java 8 或更高版本,並將 IronPDF 函式庫作為 Maven 或 Gradle 依賴項加入,且在呼叫任何 IronPDF 功能之前,必須透過 License.setLicenseKey() 設定有效的授權金鑰。無需任何原生 PDF 工具或額外框架。

removePage 會修改原始 PDF 檔案嗎?

不。removePageremovePages 會修改記憶體中的 PdfDocument 物件。磁碟上的原始檔案將保持不變,直到您呼叫 pdf.saveAs(Path.of("output.pdf")) 將修改後的文件寫入新路徑為止。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

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