iText – PDF Java Library

iText is the most popular library to create, read and update PDF document. Here is a good example to start using it.

itext

Objective:

  • Create your first PDF using iText for Java

Environment & Tools:

  • Eclise
  • Maven

Library:

<dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.2</version>
    </dependency>

( 1 ) Hello World

package com.hmkcode;

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

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

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

        	// 1. create the document
        	Document document = new Document();
        	// 2. get PdfWriter
			PdfWriter.getInstance(document, new FileOutputStream("helloworld.pdf"));
			// 3. open the document
	        document.open();
	        // 4. add the content
	        document.add(new Paragraph("Hello World!"));
	        // 5. close the document
	        document.close();

	        System.out.println("Document created!");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}      
    }
}

output: helloworld.pdf

( 2 ) Setting Page Size and Margins

  • We can set the page size using the pre-defined PageSize class.
  • We can define our page size using Rectangle
Document document = new Document(PageSize.A4, 20f,20f,40f,40);
 Rectangle pagesize = new Rectangle(216f, 720f);
        	 Document document = new Document(pagesize, 20f,20f,40f,40);

Source Code @ GitHub