Create a small Java program that demonstrates a few capabilities of iText library. You will learn how to create a document, add a pdf writer (listener), add some content to the created document, and last, but not least, close the document.
This is just a quick intro to the creation of PDF files with Java, if you’re serious about automatic PDF creation using Java, then read Bruno Lowagie’s tutorial (link at the end).
- Make sure you have Java Runtime Environment, Eclipse and iText installed.
-
Step 2
In Eclipse create a new project, and name it what ever you might like at that particular moment. Then right click on the project name > Properties > Java Build Path > Add External JARs > Find your iText-2.1.5.jar > Press open > Press Ok.
-
Step 3
Create a document object:
Document document = new Document(); -
Step 4
Create a writer that listens to the document and directs a PDF stream to a file:
FileOutputStream fos = new FileOutputStream(“c://ElloUniverse.pdf”);
PdfWriter.getInstance( document, fos ); -
Step 5
Open the pdf document using this java code:
document.open(); -
Step 6
Add some text (i.e. two paragraphs) to your PDF document:
document.add(new Paragraph(“ELLO UNIVERSE!!!”));CMYKColor color = new CMYKColor( 0, 1, (float)0.2, (float)0.667 );
String text = “kievan wrote more: different color and font type.”;
Font o = FontFactory.getFont( FontFactory.TIMES_BOLD, 14, Font.BOLD, color );
Paragraph p = new Paragraph( text, o );document.add( p );
-
Step 7
Close the PDF document:
document.close(); -
Step 8
//This is the complete
//Java source code that
//generates a PDF document.
// ElloUniverse.java //
///////////////////////import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.pdf.CMYKColor;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.*;public class ElloUniverse
{
public static void main(String[] args)
{
System.out.println(“ELLO UNIVERSE!!!”);// create a document object
Document document = new Document();try
{
// create a writer that listens to the document
// and directs a PDF-stream to a file
FileOutputStream fos = new FileOutputStream(“c:\\ElloUniverse.pdf”);
PdfWriter.getInstance( document, fos );// open the document
document.open();// add a couple of paragraphs to the document
document.add(new Paragraph(“ELLO UNIVERSE!!!”));CMYKColor color = new CMYKColor( 0, 1, (float)0.2, (float)0.667 );
String text = “kievan wrote more: different color and font type.”;
Font o = FontFactory.getFont( FontFactory.TIMES_BOLD, 14, Font.BOLD, color );
Paragraph p = new Paragraph( text, o );document.add( p );
}
catch (DocumentException de)
{
System.err.println(de.getMessage());
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
}// close the document
document.close();
}
}