PDFBox - Loading a Document


Advertisements

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

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

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.

Step 3: Saving the 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");

Step 4: Closing the Document

Finally close the document using the close() method of the PDDocument class as shown below.

document.close();

Example

Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot.

Loading Document

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.

Additional page in Document
Advertisements