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.
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.
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);
Perform the required operations such as adding pages adding text, adding images to the loaded document.
After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");
Finally close the document using the close() method of the PDDocument class as shown below.
document.close();
Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot.
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 − 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(); } }
Compile and execute the saved Java file from the command prompt using the following commands
javac LoadingExistingDocument.java java LoadingExistingDocument
Upon execution, the above program loads the specified PDF document and adds a blank page to it displaying the following message.
PDF loaded
If you verify the specified path, you can find an additional page added to the specified PDF document as shown below.