How to Create a PDF File in Java
The Portable Document Format (PDF) was created in the early 1990s by Adobe. The primary motivation behind the creation of the PDF file format was to make the viewing of read-only files available to both Microsoft and Macintosh systems. The PDF format gained such popularity that it was formally adopted as an International Standard in 2008. Since the adoption as a standard, the number of file libraries and programming interfaces available to manipulate the PDF format has increased. The iText open source project has emerged to allow Java programmers to save and manipulate data documents to the PDF format.
Instructions
-
-
1
Download the freely available iText PDF manipulation library for Java (see link in Resources section below).
-
2
Include the standard FileOutputStream and IOException classes from the java.io.* library as well as the com.lowagie.text.* and com.lowagie.text.pdf.PdfWriter libraries from the lowagie java libraries.
-
-
3
Instantiate a new Document class object. For this example the document will be basic, but you can also pass other information (or documents) to this instance of the class to write to PDF.
Document myDocument = new Document();
-
4
Get an instance of the PdfWriter class with the basic document and a handle of a new FileOutputStream object that contains the name of the sample PDF file being created.
try {
PdfWriter.getInstance(document,
new FileOutputStream("myJavaPdfFile.pdf")); -
5
Open the document being created and add a new paragraph to the file. IO exceptions for both the IO stream as well as the document stream are handled after the document object manipulation.
document.open();
document.add(new Paragraph("Hello World. I wrote this in Java!!"));
}
catch (DocumentException de) {
System.err.println(de.getMessage());
}
catch (IOException ioe) {
System.err.println(ioe.getMessage());
} -
6
Close the document and view the new PDF file.
document.close();
}
}
-
1
Tips & Warnings
The iText JAVA API is able to do complex PDF file manipulation to include adding your own watermarks to documents, and RTF and HTML file manipulation.
Adobe also provides a JAVA API that performs similar functions to the iText API.