java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to create a PDF document using iText?

This example is the first example of the iText series on how to use the iText library to create a PDF document.

In this example we show how to use the Document class, getting an instance of PdfWriter, etc. Creating a simple Paragraph and set the text alignment and the font. Let see the code below:

package com.javacoderanch.example.lowagie;

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.File;
import java.io.FileNotFoundException;

public class PDFDocumentCreate {
    public static void main(String[] args) {

        //
        // Create a new document.
        //
        Document document = new Document();

        try {
            //
            // Get an instance of PdfWriter and create a HelloWorld.pdf file as an output.
            //
            PdfWriter.getInstance(document, new FileOutputStream(new File("HelloWorld.pdf")));
            document.open();

            //
            // Create our first paragraph for the pdf document to be created. We also set
            // the alignment and the font of the paragraph.
            //
            String text = "Java Code Ranch website provides beginners to Java programming some examples " +
                    "to use the Java API (Application Programming Interface) to develop applications. " +
                    "Learning from some examples will hopefully decrease the time required to learn Java.";
            Paragraph paragraph = new Paragraph(text);
            paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
            paragraph.setFont(new Font(Font.HELVETICA, 10, Font.NORMAL));
            
            document.add(paragraph);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}