PDFBox - Loading a Document



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 loadPDF() of the Loader class. This method accepts a RandomAccessReadBufferedFile object as a parameter, since this is a static method you can invoke it using class name as shown below.

// Loading an existing document 
PDDocument document = Loader.loadPDF(
   new RandomAccessReadBufferedFile("D:/Projects/PDFBox/PdfBox_Examples/sample.pdf"));

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 - Loading existing document

Suppose we have a PDF document which contains a single page, in the path, D:/Projects/PDFBox/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 PDFBoxDemo.java.

PDFBoxDemo.java

package com.tutorialspoint.pdfbox;

import java.io.IOException;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class PDFBoxDemo {

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

      // Loading an existing document 
      PDDocument document = Loader.loadPDF(
         new RandomAccessReadBufferedFile("D:/Projects/PDFBox/PdfBox_Examples/sample.pdf")); 

      System.out.println("PDF loaded"); 

      //Adding a blank page to the document 
      document.addPage(new PDPage());  

      //Saving the document 
      document.save("D:/Projects/PDFBox/PdfBox_Examples/sample.pdf");

      //Closing the document  
      document.close();         
   }  
}

Output

Compile and run the code to verify the following output −

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