Creating PDF-files with iText

After the installation of your Java editor, JSDK’s and setting the right class path to the iText.jar file you can start with your code in Java to create a PDF file.

First Class

Just start your class as learned in the Java assignments:

import java.io.FileOutputStream;
import java.io.IOException;
public class Testcase {
public static void main(String[] args) {
// code goes here
}
}

Add iText libaries

Now you need to import the iText libraries:

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
public class Testcase {
public static void main(String[] args) {
// code goes here
}
}

Creating a document

Next, you can add a new document:

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
public class Testcase {
public static void main(String[] args) {
System.out.println(“Printing PDF file ..”);
Rectangle pageSize = new Rectangle(0,0,2382,3369);
Document document = new Document(pageSize);
}
}

The System.out.println is a check to see if the creation of the PDF file is actually called after running your application.

Document setup

pageSize is a new rectangle instance which is going to contain some properties for the document instance about for example: size and color. The com.lowagie.text.Document object has 3 constructors:

public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);

The first constructor calls the second one, with PageSize.A4 as parameter. The second constructor calls the third one, with 36 as value for each margin. So also possible is for example:

Document document = new Document(PageSize.A0);

PageSize.A0 automatically assigns the right values for a A0 size to the document instance. Further options are: A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA and FLSE.

Once our document is created, we can create one or more instances of writers that listen to this document. All writers should be derived from the abstract class com.lowagie.text.DocWriter. For the moment there are two possibilities: you can use com.lowagie.text.pdf.PdfWriter to generate documents in the Portable Document Format, or you can use com.lowagie.text.html.HtmlWriter to generate documents in HTML. If for instance you want to generate TeX-documents as well, you could write a package: m.lowagie.text.TeX.TeXWriter.

You can create an instance this way:

dfWriter.getInstance(document, new FileOutputStream(“filename.pdf”));

So including the exceptions you’ll get:

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
public class Testcase {
public static void main(String[] args) {
System.out.println(“Printing PDF file ..”);
Rectangle pageSize = new Rectangle(0,0,2382,3369);
Document document = new Document(pageSize);
try { PdfWriter.getInstance(document, new FileOutputStream(“filename.pdf”));}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
catch(IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}

Visuals

Now it’s time to get some visuals into the PDF file. What you’ll have to is open the document, add graphics and then close the document. In this example we add a line to the document that says: “Hi, this is your PDF file!”

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
public class Testcase {
public static void main(String[] args) {
System.out.println("Printing PDF file ..");
Rectangle pageSize = new Rectangle(0,0,2382,3369);
Document document = new Document(pageSize);
try {
PdfWriter.getInstance(document, new FileOutputStream("filename.pdf"));
document.open();
document.add(new Paragraph("Hi, this is your PDF file!"));
}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
catch(IOException ioe) {
System.err.println(ioe.getMessage());
}
document.close();
}
}

Compile

Just compile and run this piece of code and you PDF file is created. If you open the PDF file the text is quite small, that’s because it’s on A0 format.

For more complex possibilities and features read the tutorials on:

18 thoughts on “Creating PDF-files with iText”

  1. Sir,
    I am trying to upload a text file into PDF format, and i am using NetBeans IDE 6.0.1. I have to add a java pdf library to NetBeans IDE application. How can I add java pdf library to NetBeans IDE application.

    Please reply to my e-mail.

    Thanks and Regards,
    Anand

  2. yo could add is you see the project tab at the booton there is afolder that says libraries righ click on the folder

  3. then chose add jar folder

    then chose the jar file and is ready the compilation is now part of your project and you could use the packages by importint

    i hope will help you

  4. Thanks! This was very helpful! Short, sweet and no need to sift through tutorials to get started. :)

  5. it is so use full to my project . thanks so much
    *************************************************

  6. I have an open document I am writing to. Instead of adding a new Paragraph Element, what if I want to write the entire contents of an existing PDF File?

  7. I have a problem con iText I need generate a document in landscape orientation; for that I imported a pdf file and write on it, the pdf that I import is in letter horizontal position, when the program generates the result pdf, the application always gave me a document with portrait position, the text that program puts in document are in correct orientation but the document are wrong orientation, I don’t know why the code read the base pdf in landscape position and gave one in portrait, the page size are read and asigned with these commands

    Rectangle pageSize = reader.getPageSize(1);
    document = new Document(pageSize);

    If I use the method rotate in
    document = new Document(pageSize.rotate());

    I obtain a document in landascape but the base pdf are in portrait position and cutted by the size of the page

    I don’t know how do for obtain a pdf in landascape position. :( correctly

    Please Help me

  8. @Luis: it’s already a while ago that you have posted that question, so I assume that you have solved the problem. Anyway, here’s my solution:

    Rectangle a4 = PageSize.A4;
    Rectangle a4Landscape = a4.rotate();
    Document doc = new Document(a4Landscape);

    For me, it works like a charm… The paper is in landscape format and the content is written in the correct orientation.

  9. Rotated Rectangle with stroking not printed accurately while PDF Generating

  10. hi i am experiencing some difficulties such that my program has an error and it tells me the package com.lowagie.text does not exist even after importing iText 2.0 please help

  11. Hi I have a problem when sending print the PDF document created adobe reader tells me that can not display this site and reviewing and only happens when I add lines, remove them and no error appears, I leave the code as the sample probe page of the creators and nothing itext

    Imports iTextSharp.text.Document
    Imports iTextSharp.text.pdf
    Imports iTextSharp.text
    Imports iTextSharp.text.pdf.PdfWriter
    Imports System.IO

    MemStream Dim As New MemoryStream ()
    Dim As iTextSharp.text.pdf.PdfWriter pdfw
    Dim cb As PdfContentByte
    DocumentPDF Dim As Document = New Document ()
    DocumentPDF = New Document (iTextSharp.text.PageSize.LETTER, 0, 0, 0, 0)

    ‘Open the document
    DocumentPDF.Open ()
    cb = pdfw.DirectContent
    ‘Add a page.
    DocumentPDF.NewPage ()
    ‘Start the Text
    cb.BeginText ()

    cb.SaveState ()
    cb.SetLineWidth (8)
    cb.SetLineCap (5)
    cb.MoveTo (350, 500)
    cb.LineTo (540, 500)
    cb.Stroke ()
    cb.RestoreState ()

    cb.EndText ()
    pdfw.Flush ()
    ‘Dim As jAction PdfAction.JavaScript PDFACTION = (“this.notprint (true);” & vbCr, pdfw)
    ‘Pdfw.AddJavaScript (jAction)
    ‘Close the document
    DocumentPDF.CloseDocument ()

  12. You can create PDF file with Aspose’s Java Component for PDF file known as Aspose.PDF for Java. This Library offers many other features for PDF file that developers can use in their Application.

  13. My pdf is generating and also displaying page numbers(at bottom) of every pdf page.I am displaying table of contents in my pdf but i need to know how to get exact location(page number) of each section of dynamically generated PDF so that I can write Table Of contents with page numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *