如何在Java中删除PDF中的页面

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

使用 IronPDF for Java 删除 PDF 页面非常简单:该库提供了由 PageSelection 支持的 removePageremovePages 方法,让您能够精确控制要删除的页面——无论是单页、连续范围还是分散的页面索引。 IronPDF中的所有页面索引都是从零开始的,所以文档的第一页的索引总是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 导入 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>removePages</code>与<code>PageSelection</code>删除多个页面或一个范围</li>
        <li>使用<code>saveAs</code>保存修改后的PDF</li>
    </ol>
</div>

## 开始之前我需要什么?

在从PDF中删除页面之前,确认IronPDF已在您的Java项目中配置。 该库需要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 导入 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中删除一系列页面?

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
导入 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
导入 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,请始终从最高索引开始向低索引方向处理。若先移除索引较低的页面,会导致所有较高索引的页面向下移动一位,从而导致后续调用指向错误的页面。 从文档末尾开始向后工作,每次删除都会保持剩余的低索引不被打扰。

下面的示例删除一个六页文档的第一页、中间页和最后一页。 调用从最高到最低索引排列 -- 5、3、0 -- 以防止索引漂移。

//:path=/static-assets/ironpdf-java/content-code-examples/how-to/java-delete-pdf-pages-tutorial/non-consecutive-pages.java
导入 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
导入 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
导入 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
导入 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))调用。从和到索引均从零开始且包括在内。例如,PageSelection.pageRange(2, 4)在单次原子操作中删除文档的第三、第四和第五页。

为什么需要从高索引到低索引删除页面?

当您多次调用removePage时,每次删除都会将所有后续页面索引下移一位。从高索引到低索引删除确保每次调用都针对正确的页面,因为还没有较低索引的页面被删除导致移动。

IronPDF Java中的PageSelection是什么?

PageSelection是位于com.ironsoftware.ironpdf.edit包中的一个类,它定义了一个方法应针对哪些页面。PageSelection.pageRange(fromIndex, toIndex)创建一个覆盖一块连续零起始、包容的页面索引的选择,以用于removePages

使用IronPDF在Java中删除PDF页面的前提条件是什么?

您需要Java 8或更高版本,作为Maven或Gradle依赖项添加IronPDF库,并使用License.setLicenseKey()设置一个有效的许可证密钥,然后才能进行任何IronPDF调用。不需要原生PDF工具或额外的框架。

removePage会修改原始PDF文件吗?

不。removePageremovePages修改内存中的PdfDocument对象。磁盘上的原始文件未受影响,直到您调用pdf.saveAs(Path.of("output.pdf"))将修改后的文档写入新路径。

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。

准备开始了吗?
版本: 2026.5 just released
Still Scrolling Icon

还在滚动吗?

想快速获得证据?
运行示例看着你的HTML代码变成PDF文件。