For creating a PDF document using Java, we need to know the packages/libraries which are necessary for writing the code. So, for creating a PDF doc, we will be using the iText 7 library. To know how to install this library in your workspace, you can follow this link.
Creating An Empty PDF Doc
To create an empty PDF Document, we first need to instantiate the Document class, and while doing so, we have to pass a PdfDocument object as an argument. The following are the components used in creating an empty PDF doc.
The PdfWritter class belongs to the package com.itextpdf.kernel.pdf. We can say that this class is the Doc Writer for a PDF. While instantiating an object of PdfWritter object, we have to pass a string value, which represents the path of the file, where we want the PDF to be created.
Note: While passing the path of the file, make sure that your IDE has the permission to write/read files in that directory, otherwise, it will give a FileNotFound error.
String path = "C:/JavaExamples/exmple.pdf"; PdfWriter writer = new PdfWriter(path);
The PdfDocument class belongs to the package com.itextpdf.kernel.pdf. This class represents the PDF Document. While instantiating this class, we have to pass the PdfWriter object as an argument.
//writer is the PdfWriter object PdfDocument pdf = new PdfDocument(writer);
The Document class belongs to the package com.itextpdf.layout. It is one of the core classes in IText. If you want to generate a PDF from scratch, then you must use Document Class. While instantiating the Document class, we need to pass the PdfDocument object as an argument.
Syntax to create a Document Object:
//pdf is the PdfDocument object Document doc = new Document(pdf);
4. Closing the Document
Close the document using the close() method of the Document class as shown below.
// Closing the document doc.close();
- This is an empty document, you may get an error while opening this PDF because this is a PDF with 0 pages.
- You may get a FIileNotFound error if you don’t have the permission to write/read files in that directory, so you can run your IDE as an administrator, then it will work.
Now let’s create a PDF with an empty page.
Let’s open that PDF.
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.