Hack 88 Use Java to Create PDF

figs/moderate.gif figs/hack88.gif

Generate PDF from within your Java program.

When you're programming in Java, the free iText library should serve most of your dynamic PDF needs. Not only can you create PDF, but you can also read existing PDFs and incorporate their pages into your new document. Visit http://www.lowagie.com/iText/ for documentation and downloads. You can download an alternative, development branch from http://itextpdf.sourceforge.net.

Another free PDF library written in Java is Etymon's PJX (http://etymon.com/epub.html). It supports reading, combining, manipulating, and writing PDF documents.

When creating a new PDF, iText can add text, bitmaps, and drawings. Formatting includes running headers and footers, lists, and tables. PDF features include page labels, links, encryption, metadata, bookmarks, and annotations. Programming features include callbacks and templates.

You can also use iText to manipulate existing PDF pages. For example, you can combine pages to create a new document [Hack #89] or use a PDF page as the background for your new PDF [Hack #90] .

Here is Hello World! using iText:

// Hello World in Java using iText, adapted from the iText tutorial

import java.io.FileOutputStream;

import java.io.IOException;

// the iText imports

import com.lowagie.txt.*;

import com.lowagie.text.pdf.PdfWriter;

public class HelloWorld {

  public static void main(String[] args) {

    Document pdf= new Document( );

    PdfWriter.getInstance(pdf, new FileOutputStream("HelloWorld.pdf"));

    pdf.open( );

    pdf.add(new Paragraph("Hello World!"));

    pdf.close( );