Create PDF With iText Java Tutorial

Creating PDF with java in enterprise applications is quite common these days.

iText is a free and open source library for creating and manipulating PDF files in Java. It was written by Bruno Lowagie, Paulo Soares, and others. It enables developers looking to enhance web and other applications with dynamic PDF document generation and/or manipulation.

Note : itext-5.1.2.jar – Set in classpath to access and make pdf.

Developers can use iText to:

  • Serve PDF to a browser
  • Generate dynamic documents from XML files or databases
  • Use PDF’s many interactive features
  • Add bookmarks, page numbers, watermarks, etc.
  • Split, concatenate, and manipulate PDF pages
  • Automate filling out of PDF forms
  • Add digital signatures to a PDF file

Text is used in projects that have one of the following requirements:

  • The content isn’t available in advance: it’s calculated based on user input or real-time database information.
  • The PDF files can’t be produced manually due to the massive volume of content: a large number of pages or documents.
  • Documents need to be created in unattended mode, in a batch process.
  • The content needs to be customized or personalized; for instance, the name of the end user has to be stamped on a number of pages.

Create PDF With iText


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class CreatePDFWithItext{

public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("C:\\example.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.add(new Paragraph("Hello World"));
document.add(new Paragraph("http://www.javamagic.wordpress.com/"));
document.add(new Paragraph(new Date().toString()));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Hope you will like this. Cheers… 🙂