Pdfbox 简明教程
PDFBox - Loading a Document
在前面的示例中,你已经看到了如何新建文档并向其中添加页。本节将教你如何加载系统中已存在的 PDF 文件,并对其执行一些操作。
In the previous examples, you have seen how to create a new document and add pages to it. This chapter teaches you how to load a PDF document that already exists in your system, and perform some operations on it.
Loading an Existing PDF Document
PDDocument 类的 load() 方法用于加载一个现有的 PDF 文件。遵循下面给出的步骤来加载一个现有的 PDF 文件。
The load() method of the PDDocument class is used to load an existing PDF document. Follow the steps given below to load an existing PDF document.
Step 1: Loading an Existing PDF Document
使用 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);
Step 2: Perform the Required Operations
执行所需的操作,如向加载的文档中添加页、添加文本、添加图像。
Perform the required operations such as adding pages adding text, adding images to the loaded document.
Example
假设我们有一个 PDF 文档,它包含一个页面,路径为 C:/PdfBox_Examples/ ,如下图所示。
Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot.
此示例演示如何加载现有 PDF 文档。此处,我们将加载上述 sample.pdf PDF 文档,向其中添加一页,并以相同名称保存在同一路径中。
This example demonstrates how to load an existing PDF Document. Here, we will load the PDF document sample.pdf shown above, add a page to it, and save it in the same path with the same name.
Step 1 - 将此代码保存到名为 LoadingExistingDocument.java. 的文件中
Step 1 − Save this code in a file with name LoadingExistingDocument.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
public class LoadingExistingDocument {
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);
System.out.println("PDF loaded");
//Adding a blank page to the document
document.addPage(new PDPage());
//Saving the document
document.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
document.close();
}
}
使用以下命令,从命令提示符中编译并执行已保存的 Java 文件
Compile and execute the saved Java file from the command prompt using the following commands
javac LoadingExistingDocument.java
java LoadingExistingDocument
执行后,上述程序将加载指定的 PDF 文件,并向其中添加一个空白页,显示如下消息。
Upon execution, the above program loads the specified PDF document and adds a blank page to it displaying the following message.
PDF loaded
如果验证指定的路径,您可以找到一个附加到指定的 PDF 文档中的其他页面,如下所示。
If you verify the specified path, you can find an additional page added to the specified PDF document as shown below.