Adding Pages to a PDF Document using Java
PDDocument class of ‘org.apache.pdfbox.pdmodel’ package which extends ‘java.lang.Object‘. is used.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
public class PDDocument extends Object implements Pageable, Closeable
- PDDocument(): This constructor used to construct a new PDF document with zero pages.
- PDDocument(COSDocument doc): This constructor uses already existing PDF documents, and then we can add or remove pages.
- PDDocument(COSDocument doc, BaseParser usedParser): This constructor is similar to the above one but it has a parser in it.
Method Using: addPage() Method
There are many methods in PDDocument class but standard and most frequently used to add anything to PDF be it image or pages, the requirement is only for addPage() method. The addPage() method is used for adding pages in the PDF document. The following code adds a page in a PDF document.
Syntax: To declare addPage() method
public void addPage(PDPage page) ;
This will add a page to the document. This is the easiest method, which will add the page to the root of the hierarchy and set the parent of the page to the root. Hence, so far by now, the page to be added to the document is defined clearly.
- Create a document.
- Create a blank page.
- Add this page to the document.
- Save the document.
- Close the document.
Step 1: Creating a Document
An object is needed to be created of PDDocument class which will enable the creation of an empty PDF document. Currently, it does not contain any page.
PDDocument doc = new PDDocument();
Step 2: Creating a Blank Page
PDPage is also a type of class that belongs to the same package as PDDocument which is ‘org.apache.pdfbox.pdmodel‘.
PDPage page = new PDPage();
Step 3: Adding Page to Document
Here, addPage() method of PDDocument class is used to add the blank to the document which is nothing but an object of PDDocument.
PDPage page = new PDPage();
Step 4: Saving the Document
After adding pages to the document you have to save that file at the desired location for that we use the save() method which takes a string as a parameter containing the path address.
Step 5: Closing Document
Finally, we have to close the document by using the close() method. If we don’t close it then if another program wants to access that PDF then it will get an error.
Note: By now there is only 1 page in the PDF document as shown in the markup[1/1] in the above output image.
Note: By now, a page has been added to the above image page which is evidently seen in the markup [1/2] in the above output image.