Generating PDF in Java Using iText Tutorial

This iText tutorial shows how to generate PDF in Java using iText.

Before going to examples of PDF creation in Java using iText there are few points about iText library.

  1. iText (https://itextpdf.com) comes with dual licenses commercial as well as open source (AGPL). If you are using AGPL license (which is free) you need to share your entire application for free under the same AGPL license.
  2. The examples shown in this post use iText 7 library which is rewritten and API differs from iText 5.
  3. Some of the main classes that are used for generating PDF using iText are-
    Document– Document is the default root element when creating a self-sufficient PDF.
    PDFDocument– Main enter point to work with PDF document.
    Paragraph– Creates a Paragraph, initialized with a piece of text.
    Text– A Text is a piece of text of any length.
    PdfWriter– Create a PdfWriter writing to the passed outputstream.
    PdfReader– Reads a PDF document.
    PdfFontFactory– This class provides helpful methods for creating fonts ready to be used in a PdfDocument.
    Table– A Table is a layout element that represents data in a two-dimensional grid.

Maven dependency

For using iText 7 library core modules you need to add iText 7 Core as a dependency to your pom.xml file. Maven will automatically download all the required modules from the repository.

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <itext.version>7.1.6</itext.version>
</properties>
<dependencies>
  <!-- add all iText 7 Community modules -->
  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>${itext.version}</version>
    <type>pom</type>
  </dependency>
</dependencies>

Examples of PDF generation using iText and Java given in this post.

HelloWorld PDF Creation Java and iText example

We’ll start with creating a simple HelloWorld PDF along with font and text color settings.

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;

public class HelloWorldPDF {
  public static final String CREATED_PDF = "F://knpcode//result//HelloWorld.pdf";
  public static void main(String[] args) {
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(CREATED_PDF));
      PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
      PdfDocument pdf = new PdfDocument(writer);
      Document document = new Document(pdf);
      Text text = new Text("Hello World PDF created using iText")
                  .setFont(font)
                  .setFontSize(15)
                  .setFontColor(ColorConstants.MAGENTA);
      //Add paragraph to the document
      document.add(new Paragraph(text));
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }  
  }
}

Hello world pdf iText

PDF with Style for content styling

import java.io.IOException;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;

public class HelloWorldPDF {
  public static final String CREATED_PDF = "F://knpcode//result//Styled.pdf";
  public static void main(String[] args) {
    try {
      PdfDocument pdf = new PdfDocument(new PdfWriter(CREATED_PDF));				
      PdfFont font = PdfFontFactory.createFont(StandardFonts.COURIER);
      Style style = new Style().setFont(font)
                               .setFontSize(14)
                               .setFontColor(ColorConstants.RED)
                               .setBackgroundColor(ColorConstants.YELLOW);
				 
      Document document = new Document(pdf);
      document.add(new Paragraph()
              .add("In this PDF, ")
              .add(new Text("Text is styled").addStyle(style))
              .add(" using iText ")
              .add(new Text("Style").addStyle(style))
              .add("."));
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }  
  }
}

Style PDF iText

Converting text file to PDF using iText

In the Java example there is a text file (Test.txt) which is converted to a PDF using iText.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

public class TextToPDF {
  public static final String SOURCE_FILE = "F://knpcode//result//Test.txt";
  public static final String CREATED_PDF = "F://knpcode//result//Result.pdf";
  public static void main(String[] args) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(SOURCE_FILE));
      PdfDocument pdf = new PdfDocument(new PdfWriter(CREATED_PDF));	
      Document document = new Document(pdf);
      String line;
      PdfFont font = PdfFontFactory.createFont(StandardFonts.COURIER);
      while ((line = br.readLine()) != null) {
        document.add(new Paragraph(line).setFont(font));
      }
      br.close();
      document.close();   
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Generating PDF with table

For this example we’ll use a bean class Employee and the list of employees is presented in a table in the PDF using Java program.

public class Employee {
  private String name;
  private String dept;
  private int salary;

  Employee(String name, String dept, int salary){
    this.name = name;
    this.dept = dept;
    this.salary = salary;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getSalary() {
    return salary;
  }
  public void setSalary(int salary) {
    this.salary = salary;
  }
  public String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;

public class PDFWithTable {
  public static final String CREATED_PDF = "F://knpcode//result//Employee.pdf";
  public static void main(String[] args) {
    List<Employee> employees = new ArrayList<Employee>();
    employees.add(new Employee("Jack", "HR", 12000));
    employees.add(new Employee("Liza", "IT", 5000));
    employees.add(new Employee("Jeremy", "Finance", 9000));
    employees.add(new Employee("Frederick", "Accounts", 8000));
    try {
      PdfDocument pdf = new PdfDocument(new PdfWriter(CREATED_PDF));
      Document document = new Document(pdf);
      PdfFont headerFont = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
      PdfFont cellFont = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
      Table table = new Table(3);
      table.setWidth(UnitValue.createPercentValue(100));
      // adding header
      table.addHeaderCell(new Cell(1, 3)
           .setTextAlignment(TextAlignment.CENTER)
           .setBackgroundColor(ColorConstants.LIGHT_GRAY)
           .add(new Paragraph("Employee Information")
           .setFont(headerFont)));
      table.addHeaderCell(new Cell()
           .add(new Paragraph("Name")
           .setFont(headerFont)));
      table.addHeaderCell(new Cell()
           .add(new Paragraph("Dept")
           .setFont(headerFont)));
      table.addHeaderCell(new Cell()
           .add(new Paragraph("Salary")
           .setFont(headerFont)));
      // adding rows
      for(Employee emp : employees) {
        table.addCell(new Cell()
             .add(new Paragraph(emp.getName())
             .setFont(cellFont)));
        table.addCell(new Cell()
             .add(new Paragraph(emp.getDept())
             .setFont(cellFont)));
        table.addCell(new Cell()
             .add(new Paragraph(Integer.toString(emp.getSalary()))
             .setFont(cellFont)));
      }
      document.add(table);
      document.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  
  }
}

PDF Table iText

Adding image to PDF using iText

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.layout.element.Image;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

public class ImagePDF {
  public static final String IMAGE_PDF = "F://knpcode//result//Image.pdf";
  public static void main(String[] args) {
  PdfWriter writer;
  try {
    // path to image
    Image image = new Image(ImageDataFactory.create("images//iText image.png"));
    writer = new PdfWriter(new FileOutputStream(IMAGE_PDF));
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document document = new Document(pdfDoc);       
    document.add(new Paragraph("In this PDF which is created using iText an image is added"));
    // adding image
    document.add(image);		      
    document.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
  }
}

Image in PDF iText

Adding list to PDF using iText

If you want to add list items to a PDF you can do that using List and ListItem (for adding individual list items) classes.
There is an Enum ListNumberingType which has the symbols that can be used for numbering the list items.

import java.io.IOException;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.ListNumberingType;

public class PDFWithTable {
  public static final String CREATED_PDF = "F://knpcode//result//List.pdf";
  public static void main(String[] args) {
    try {
      PdfDocument pdf = new PdfDocument(new PdfWriter(CREATED_PDF));
      // List items using Roman symbols
      Document document = new Document(pdf);
      List list = new List()
                 .setSymbolIndent(8) // space from the left
                 .setListSymbol(ListNumberingType.ROMAN_LOWER);
      document.add(new Paragraph("List with Roman symbols"));			
      // Add ListItem objects
      list.add(new ListItem("Item1"))
          .add(new ListItem("Item2"))
          .add(new ListItem("Item3"));
      // Add the list
      document.add(list);
      // List items using English Alphabets
      list = new List()
                 .setSymbolIndent(8) // space from the left
                 .setListSymbol(ListNumberingType.ENGLISH_UPPER);
      document.add(new Paragraph("List with English letter symbols"));			
      // Add ListItem objects
      list.add(new ListItem("Item1"))
          .add(new ListItem("Item2"))
          .add(new ListItem("Item3"));
      // Add the list
      document.add(list);
      // List items using English Alphabets
      list = new List()
                 .setSymbolIndent(8) // space from the left
                 .setListSymbol(ListNumberingType.GREEK_LOWER);
      document.add(new Paragraph("List with Greek letter symbols"));			
      // Add ListItem objects
      list.add(new ListItem("Item1"))
            .add(new ListItem("Item2"))
            .add(new ListItem("Item3"));
      // Add the list
      document.add(list);
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }  
  }
}

List Items iText

Render PDF in web application using iText

For rendering PDF to the browser using iText requires using ServletOutputStream as a parameter with PDFWriter. You can get this OutputStream from HTTPResponse.

PdfWriter writer;
try{
  // Setting HTTPResponse content type as PDF
  response.setContentType("application/pdf");
  writer = new PdfWriter(response.getOutputStream());
  PdfDocument pdfDoc = new PdfDocument(writer);
  Document document = new Document(pdfDoc); 
  PdfFont titleFont = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
  PdfFont textFont = PdfFontFactory.createFont(StandardFonts.COURIER);
  document.add(new Paragraph("PDF generated in Web")
              .setFont(titleFont).setFontColor(ColorConstants.RED)
              .setTextAlignment(TextAlignment.CENTER));
  Paragraph p = new Paragraph("This PDF is rendered as a web response.");
  document.add(p.setFont(textFont).setFontColor(ColorConstants.ORANGE));
  document.close();
  }catch(Exception e){
      e.printStackTrace();
  }

Related Posts

That’s all for the topic Generating PDF in Java Using iText Tutorial. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.