PDDocument class of ‘org.apache.pdfbox.pdmodel’ package which extends ‘java.lang.Object‘. is used.
Declaration:
public class PDDocument extends Object implements Pageable, Closeable
Pre-requisite: Constructors
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.
Procedure:
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.
Syntax:
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‘.
Syntax:
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.
Syntax:
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.
Syntax:
doc.save("path");
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.
Syntax:
doc.close();
Implementation:
Example 1(A)