How to Generate a PDF Using Java

If you are a frequent Java developer, chances are good that you will run into the need to create PDF documents dynamically. Java lets you do this using an external library, called iText. Once the iText library is installed and configured, you can add PdfWriter objects to your Java code that create pdf files quickly and easily. The Eclipse Java IDE will also be needed to edit, run, and test your Java code, as well as make the installation of iText easier.

    Initial Configuration

  1. Step 1

    Download and install Eclipse.

  2. Step 2

    Download the iText Java Library by navigating to the “Download iText Library” link and clicking “Download Now.” The entire library is packaged as a single “.jar” file. Save the file in a place you will remember.

  3. Step 3

    Open Eclipse and click “File,” “New,” “Java Project.” Name the project “iText” and click “Finish.”

  4. Step 4

    In the “Package Explorer” (the left-hand side toolbar), double-click the “iText” folder and select “Properties.”

  5. Step 5

    Select “Java Build Path” on the left, and then click the “Libraries” tab in the window on the right.

  6. Step 6

    Click the “Add External JARs…” button. Navigate to the directory where you saved your “.jar” file and click “Open” and then “OK.” The iText library is now installed for your Java Project, and you can use it in your code to create PDFs.

  7. Creating a PDF Document

  8. Step 1

    In Eclipse, go to “File,” “New,” “Class.” Type “Test” in the Name field, under the “Which method stubs would you like to create?” select “public static void main(String[] args)” and click “Finish.”

  9. Step 2

    In the Java editor window, select the whitespace above “public Class Test {” and type or copy-paste the following three “import” statements:
    import java.io.FileOutputStream;

    import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.*;

    The first import statement allows you to create files. The last two import the iText library into the current file and allow you to generate PDFs.

  10. Step 3

    Select the white space under “public static void main(String[] args) {” and type or copy-paste the following code:
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    try{
    PdfWriter writer = PdfWriter.getInstance(document,
    new FileOutputStream(“iTextTest.pdf”));
    document.open();
    document.add(new Paragraph(“My First PDF document.”));
    document.close();
    } catch (Exception e){
    System.err.println(e.getMessage());
    }

  11. Step 4

    Click the green play button at the top of Eclipse to run your program.

  12. Step 5

    Navigate to the iText folder in your Eclipse Workspace directory. Double-click the “iTextTest.pdf” file. This is the PDF file that was created in the previous step, and it will read “My First PDF document” at the top of the page.