Create Simple PDF using Apache PDFBox
What is Apache PDFBox?
Apache PDFbox is an open source java library used for working with PDF files. We can create new files, modify existing files, read files and do many other manupulations using Apache Pdfbox.
In this post lets see the steps to create simple pdf using Apache Pdfbox library.
1. Setup the environment
For creating a simple PDF file you can use the following maven dependency
1 2 3 4 5 | <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.10</version> </dependency> |
If you are working on a simple java project you can add the following jar into the classpath
pdfbox-2.0.10.jar
You can download it from Apache PDFBox site.Apache PDFBox Downloads
Please note: for writing into the pdf you will also need another jars. We will explain that in our next post.
2. Java Code
For creating a simple pdf we require 2 important classes from the PDFBox library
a) org.apache.pdfbox.pdmodel.PDDocument;
b) org.apache.pdfbox.pdmodel.PDPage;
PDDocument is the in-memory representation of the PDF document, while PDPage is representation of a Page in the pdf file.
You can only use PDDocument for creating a file without any pages, but if you try to open the file you may get an error. Hence adding a page to the document becomes a mandatory step.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package com.kscodes.examples.pdfbox; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; public class SimplePdf { public static void main(String args[]) { // Create a Document object. PDDocument pdDocument = new PDDocument(); // Create a Page object PDPage pdPage = new PDPage(); // Add the page to the document and save the document to a desired file. pdDocument.addPage(pdPage); try { pdDocument.save("K:\\Kscodes\\pdf\\sample.pdf"); System.out.println("PDF saved to the location !!!"); pdDocument.close(); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output : A pdf gets created at the specified location.
In our next few posts we will see more examples on Apache PDFBox.