专业的JAVA编程教程与资源

网站首页 > java教程 正文

7 用Java获取页码及删除页面(PDFBOX)

temp10 2025-07-06 16:22:58 java教程 17 ℃ 0 评论

[翻译]现在让我们学习如何从PDF文档中删除页面。

[原文]Let us now learn how to remove pages from a PDF document.

7 用Java获取页码及删除页面(PDFBOX)

Learn /ln/ 学习
Remove /r'muv/ 删除
Pages /'pe.dz/ 页面
Document /'dɑ.kj.mnt/ 文档


Removing Pages from an Existing Document 从现有文档中删除页面

[翻译]您可以使用PDDocument类的removePage()方法从现有PDF文档中删除页面。

[原文]You can remove a page from an existing PDF document using the removePage() method of the PDDocument class.

Remove /r'muv/ 删除
Page /ped/ 页面
Existing /ɡ'zs.t/ 现有的
Document /'dɑ.kj.mnt/ 文档
Method /'meθ.d/ 方法


Step 1: Loading an Existing PDF Document 步骤 1:加载现有PDF文档

[翻译]使用PDDocument类的静态方法load()加载现有PDF文档。此方法接受一个文件对象作为参数,因为这是一个静态方法,您可以使用类名调用它,如下所示。

[原文]Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.

File file = new File("path of the document") 
PDDocument.load(file);

Load /lod/ 加载
Static /'staet.k/ 静态的
Method /'meθ.d/ 方法
Accepts /k'septs/ 接受
File /fal/ 文件
Object /'ɑb.dekt/ 对象
Parameter /p'raem..t/ 参数
Invoke /n'vok/ 调用


Step 2: Listing the Number of Pages 步骤 2:列出页面数量

[翻译]您可以使用getNumberOfPages()方法列出PDF文档中现有的页面数量,如下所示。

[原文]You can list the number of pages that exists in the PDF document using the getNumberOfPages() method as shown below.

int noOfPages= document.getNumberOfPages();
System.out.print(noOfPages);

List /lst/ 列出
Number /'nm.b/ 数量
Pages /'pe.dz/ 页面
Exists /ɡ'zsts/ 存在
Document /'dɑ.kj.mnt/ 文档
Method /'meθ.d/ 方法


Step 3: Removing the Page 步骤 3:删除页面

[翻译]您可以使用PDDocument类的removePage()方法从PDF文档中删除页面。在此方法中,您需要传递要删除的页面的索引值。在指定PDF文档中页面的索引时,请注意,页面索引从零开始,即如果您想删除第1页,则索引值需要为0。

[原文]You can remove a page from the PDF document using the removePage() method of the PDDocument class. To this method, you need to pass the index of the page that is to be deleted. While specifying the index for the pages in a PDF document, keep in mind that indexing of these pages starts from zero, i.e., if you want to delete the 1st page then the index value needs to be 0.

document.removePage(2);

Remove /r'muv/ 删除
Page /ped/ 页面
Document /'dɑ.kj.mnt/ 文档
Method /'meθ.d/ 方法
Pass /paes/ 传递
Index /'n.deks/ 索引
Deleted /d'li.td/ 删除
Specifying /'spes..fa./ 指定


Step 4: Saving the Document 步骤 4:保存文档

[翻译]删除页面后,使用PDDocument类的save()方法保存PDF文档,如以下代码块所示。

[原文]After removing the page, save the PDF document using the save() method of the PDDocument class as shown in the following code block.

document.save("Path");

Save /sev/ 保存
Document /'dɑ.kj.mnt/ 文档
Method /'meθ.d/ 方法


Step 5: Closing the Document 步骤 5:关闭文档

[翻译]最后,使用PDDocument类的close()方法关闭文档,如下所示。

[原文]Finally, close the document using the close() method of the PDDocument class as shown below.

document.close();

Close /kloz/ 关闭
Document /'dɑ.kj.mnt/ 文档
Method /'meθ.d/ 方法


Example 示例

[翻译]假设我们有一个名为sample.pdf的PDF文档,包含三个空白页面,如下所示。

[原文]Suppose, we have a PDF document with name sample.pdf and it contains three empty pages as shown below.

Suppose /s'poz/ 假设
Document /'dɑ.kj.mnt/ 文档
Name /nem/ 名称
Contains /kn'tenz/ 包含
Empty /'emp.ti/ 空的
Pages /'pe.dz/ 页面


[翻译]此示例演示如何从现有PDF文档中删除页面。在这里,我们将加载上述指定的PDF文档sample.pdf,从中删除一个页面,并将其保存在路径C:/PdfBox_Examples/中。将此代码保存在名为Removing_pages.java的文件中。

[原文]This example demonstrates how to remove pages from an existing PDF document. Here, we will load the above specified PDF document named sample.pdf, remove a page from it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Removing_pages.java.

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;

public class RemovingPages {

   public static void main(String args[]) throws IOException {

      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/sample.pdf");
      PDDocument document = PDDocument.load(file);
       
      //Listing the number of existing pages
      int noOfPages= document.getNumberOfPages();
      System.out.print(noOfPages);
       
      //Removing the pages
      document.removePage(2);
      
      System.out.println("page removed");

      //Saving the document
      document.save("C:/PdfBox_Examples/sample.pdf");

      //Closing the document
      document.close();

   }
}

Demonstrates /'dem.n.strets/ 演示
Remove /r'muv/ 删除
Existing /ɡ'zs.t/ 现有的
Document /'dɑ.kj.mnt/ 文档
Load /lod/ 加载
Specified /'spes..fad/ 指定的
Page /ped/ 页面
Path /paeθ/ 路径


[翻译]使用以下命令从命令提示符编译并执行保存的Java文件。

[原文]Compile and execute the saved Java file from the command prompt using the following commands.

javac RemovingPages.java 
java RemovingPages 

Compile /km'pal/ 编译
Execute /'ek.s.kjut/ 执行
Command /k'maend/ 命令
Prompt /prɑmpt/ 提示符


[翻译]执行上述程序后,将创建一个包含空白页面的PDF文档,并显示以下消息。

[原文]Upon execution, the above program creates a PDF document with blank pages displaying the following message.

3
page removed

Execution /ek.s'kju.n/ 执行
Document /'dɑ.kj.mnt/ 文档
Blank /blaek/ 空白的
Pages /'pe.dz/ 页面
Displaying /d'sple./ 显示
Message /'mes.d/ 消息


[翻译]如果您验证指定的路径,可以发现所需页面已被删除,文档中仅剩两页,如下截图所示。

[原文]If you verify the specified path, you can find that the required page was deleted and only two pages remained in the document as shown below.

Verify /'ver..fa/ 验证
Specified /'spes..fad/ 指定的
Path /paeθ/ 路径
Deleted /d'li.td/ 删除
Remained /r'mend/ 剩余
Document /'dɑ.kj.mnt/ 文档
Screenshot /'skrin.ɑt/ 截图

更好一些的写法:

package com.virhuiai.pdfbox;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import java.io.File;
import java.io.IOException;

/**
 * 用于加载现有PDF文档,删除指定页面并保存修改后的文档
 */
public class E7 {
    public static void main(String[] args) {
        // 定义输入PDF文件的路径,指定要加载的现有PDF文件
        File inputFile = new File("/Volumes/RamDisk/E2.pdf");

        // 定义输出PDF文件的路径,保存修改后的PDF文档
        File outputFile = new File("/Volumes/RamDisk/E7.pdf");

        // 使用try-with-resources确保PDDocument资源在使用完毕后自动关闭
        // PDDocument类属于org.apache.pdfbox.pdmodel包,是PDF文档的内存表示形式
        try (PDDocument document = PDDocument.load(inputFile)) {
            // 获取文档中的页面总数
            int noOfPages = document.getNumberOfPages();
            // 打印当前文档的页面数量
            System.out.println("文档当前页面数量: " + noOfPages);

            // 定义要删除的页面索引(基于0的索引)
            int pageIndexToRemove = 2;

            // 验证页面索引是否有效,避免索引越界
            if (pageIndexToRemove < 0 || pageIndexToRemove >= noOfPages) {
                throw new IllegalArgumentException(
                    String.format("无效的页面索引: %d,文档页面范围为0到%d", pageIndexToRemove, noOfPages - 1)
                );
            }

            // 删除指定索引的页面
            document.removePage(pageIndexToRemove);

            // 打印提示信息,确认页面已删除
            System.out.println("页面索引 " + pageIndexToRemove + " 已成功删除");

            // 将修改后的PDF文档保存到指定输出路径
            // save()方法接受文件路径作为参数,保存文档到指定位置
            document.save(outputFile);

            // 打印提示信息,确认PDF文档已成功保存
            System.out.println("PDF文档已成功保存至: " + outputFile.getAbsolutePath());

            // 无需显式调用close()方法,try-with-resources会自动关闭PDDocument对象
        } catch (IOException e) {
            // 捕获并处理可能发生的IO异常,例如文件不存在、路径错误或权限问题
            // 将IO异常包装为RuntimeException抛出,附带详细错误信息便于调试
            throw new RuntimeException("无法加载或保存PDF文档: " + e.getMessage(), e);
        } catch (IllegalArgumentException e) {
            // 捕获并处理无效页面索引异常,打印错误信息
            System.err.println("错误: " + e.getMessage());
            throw e;
        }
    }
}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表