How to generate PDF using iText library

In this example you will see how to create the PDF document using iText java library and how to write text in generated PDF document.

Please note we are using iText 5 version for this example.

There are some steps to follow one by one in order to create.

Create a PDF document using class com.lowagie.text.Document.

Create an OutputStream object by passing the PDF file name as you want.

Create an instance of PDF document to write using PdfWrite by passing document and OutputStream object.

Write text using Paragraph object.

Add the paragraph to document object, this will write the paragraph in PDF document.

And finally close the PDF document.

package com.java.connect.itext;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
 
public class PDFHelloWorldExample {
    public static void main(String[] args) throws DocumentException, FileNotFoundException {
        // Create new PDF document
        Document document = new Document();
        // Create an output stream of PDF file.
        OutputStream out = new FileOutputStream("PDF_Hello_World_Example.pdf");
        // Get a PdfWriter instance to write in PDF document.
        PdfWriter.getInstance(document, out);
        // Open the PDF document
        document.open();
        // Wirte a Text using Paragraph object.
        Paragraph paragraph = new Paragraph("Say hello to every body!");
        // Add paragraph to PDF document.
        document.add(paragraph);
        // Close the PDf document after use.
        document.close();
    }
}

The generated PDF file will looks like below image.

iText-hello-world-pdf-generated-example