[Tutorial] Create a PDF document with Maven and iText

Here is a quick way to start learning how to use the open-source library iText to generate PDF documents.
I start with the archetype maven-archetype-quickstart (number 101, which is the default archetype), an archetype which contains a sample Maven project.

mvn archetype:generate

You need to edit the POM.xml file to add the iText library dependency.

 <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.0.7</version>
        </dependency>

Then a couple of Maven commands and you are done :

...
mvn clean install
...
mvn exec:java -Dexec.mainClass="com.company.celinio.iText.Main"
package com.company.celinio.iText;
 
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Chunk;
import com.lowagie.text.Font;


import java.awt.Color;
import java.io.FileOutputStream;
import java.util.Date;
 
public class Main {
    public static void main(String[] args) {
        try {
            Document document = new Document();
            PdfWriter pdfWriter = 
            PdfWriter.getInstance(document, new FileOutputStream("FourthTuto.pdf"));
            
            // Properties
            document.addAuthor("Celinio");
            document.addCreator("Celinio");
            document.addSubject("iText with Maven");
						document.addTitle("Fourth tutorial");
						document.addKeywords("iText, Maven, Java");
            
            document.open();
            
            Chunk chunk = new Chunk("Fourth tutorial");
						Font font = new Font(Font.COURIER);
						font.setStyle(Font.UNDERLINE);
						font.setStyle(Font.ITALIC);
						chunk.setFont(font);
						chunk.setBackground(Color.CYAN);
						document.add(chunk);

            document.add(new Paragraph("Testing with Maven."));
            document.add(new Paragraph("Another paragraph."));
            document.add(new Paragraph(new Date().toString()));  

            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And here is the result :

Properties of the document :

Link to the video tutorial : http://www.celinio.net/tutorials/MavenTuto4.htm

Other links :
http://itextpdf.com/

Leave a Comment