Creating PDF with Java and iText - Tutorial

http://www.vogella.com/articles/JavaPDF/article.html


Lars Vogel

Version 0.5

11.10.2010

Revision History
Revision 0.128.06.2009Lars
Vogel
Created
Revision 0.2 - 0.430.06.2009 - 11.10.2010Lars
Vogel
bugfixes and enhancements

Java and PDF with iText

This article demonstrate how to create PDF files with Java and the iText library. In this tutorial iText version 5.0.x is used


1. Overview

iText is a Java library originally created by Bruno Lowagie which allows to create PDF, read PDF and manipulate them. The following tutorial will show how to create PDF files with iText. This tutorial assumes that you have basis Java and Eclipse knowledge.

iText has a hierarchical structure. The smallest text unit is a "Chunk" which is a String with a pre-defined font. A "Phrase" combines several Chunks and allows to define line spacing. "Paragraph" is a subclass of "Phrase" and allows to define more layout attributes, e.g. margins. The class "Anchor" is a subclass of "Paragraph" and serves as the basis for hyperlinks in the generated PDF.

2. Installation

Download the iText core binary from the webpage http://sourceforge.net/projects/itext/ . The download contains one jar which is required if you want to use iText.

3. Create a PDF

Create a new Java project "de.vogella.itext.write" with the package "de.vogella.itext.write". Create a folder "lib" and put the iText library (jar file) into this folder. Add the jar to your classpath.

Create the following class "FirstPdf.java" . I assume that the coding is pretty much self-explaining. I tried to add lots of comments to make it easier to understand. For more complex examples have a look at the iText Homepage .

package de.vogella.itext.write;

import java.io.FileOutputStream;
import java.util.Date;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


public class FirstPdf {
  private static String FILE = "c:/temp/FirstPdf.pdf";
  private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
      Font.BOLD);
  private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
      Font.NORMAL, BaseColor.RED);
  private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
      Font.BOLD);
  private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
      Font.BOLD);

  public static void main(String[] args) {
    try {
      Document document = new Document();
      PdfWriter.getInstance(document, new FileOutputStream(FILE));
      document.open();
      addMetaData(document);
      addTitlePage(document);
      addContent(document);
      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // iText allows to add metadata to the PDF which can be viewed in your Adobe
  // Reader
  // under File -> Properties
  private static void addMetaData(Document document) {
    document.addTitle("My first PDF");
    document.addSubject("Using iText");
    document.addKeywords("Java, PDF, iText");
    document.addAuthor("Lars Vogel");
    document.addCreator("Lars Vogel");
  }

  private static void addTitlePage(Document document)
      throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);
    // Lets write a big header
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ",
        smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
        redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
  }

  private static void addContent(Document document) throws DocumentException {
    Anchor anchor = new Anchor("First Chapter", catFont);
    anchor.setName("First Chapter");

    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Subcategory 1", subFont);
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Hello"));

    subPara = new Paragraph("Subcategory 2", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Paragraph 1"));
    subCatPart.add(new Paragraph("Paragraph 2"));
    subCatPart.add(new Paragraph("Paragraph 3"));

    // Add a list
    createList(subCatPart);
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subCatPart.add(paragraph);

    // Add a table
    createTable(subCatPart);

    // Now add all this to the document
    document.add(catPart);

    // Next section
    anchor = new Anchor("Second Chapter", catFont);
    anchor.setName("Second Chapter");

    // Second parameter is the number of the chapter
    catPart = new Chapter(new Paragraph(anchor), 1);

    subPara = new Paragraph("Subcategory", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("This is a very important message"));

    // Now add all this to the document
    document.add(catPart);

  }

  private static void createTable(Section subCatPart)
      throws BadElementException {
    PdfPTable table = new PdfPTable(3);

    // t.setBorderColor(BaseColor.GRAY);
    // t.setPadding(4);
    // t.setSpacing(4);
    // t.setBorderWidth(1);

    PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Table Header 2"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Table Header 3"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);

    table.addCell("1.0");
    table.addCell("1.1");
    table.addCell("1.2");
    table.addCell("2.1");
    table.addCell("2.2");
    table.addCell("2.3");

    subCatPart.add(table);

  }

  private static void createList(Section subCatPart) {
    List list = new List(true, false, 10);
    list.add(new ListItem("First point"));
    list.add(new ListItem("Second point"));
    list.add(new ListItem("Third point"));
    subCatPart.add(list);
  }

  private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
      paragraph.add(new Paragraph(" "));
    }
  }
} 

The resulting pdf should look like the following.

4. Formatting your output

Paragraph allows to set the alignment and the indentation. For this example create project "de.vogella.itext.position" similar to the previously created ones. Create the following class "PositionPdf.java".

package de.vogella.itext.position;

import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class PositionPdf {
  private static String FILE = "PositionPdf.pdf";

  public static void main(String[] args) {
    try {
      Document document = new Document();
      PdfWriter.getInstance(document, new FileOutputStream(FILE));
      document.open();
      // Left
      Paragraph paragraph = new Paragraph("This is right aligned text");
      paragraph.setAlignment(Element.ALIGN_RIGHT);
      document.add(paragraph);
      // Centered
      paragraph = new Paragraph("This is centered text");
      paragraph.setAlignment(Element.ALIGN_CENTER);
      document.add(paragraph);
      // Left
      paragraph = new Paragraph("This is left aligned text");
      paragraph.setAlignment(Element.ALIGN_LEFT);
      document.add(paragraph);
      // Left with indentation
      paragraph = new Paragraph("This is left aligned text with indentation");
      paragraph.setAlignment(Element.ALIGN_LEFT);
      paragraph.setIndentationLeft(50);
      document.add(paragraph);

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

} 

5. Read an existing pdf

iText allows to read existing pdf's and include them into your own pdf. The following example will create page 2 of the previous example and create a new document with this page.

Create a new Java project "de.vogella.itext.readpdf" with the package "de.vogella.itext.read". Create a folder "lib" and put the iText library (jar file) into this folder. Add the jar to your classpath. Create the following class "ReadAndUsePdf.java".

package de.vogella.itext.read;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class ReadAndUsePdf {
  private static String INPUTFILE = "c:/temp/FirstPdf.pdf";
  private static String OUTPUTFILE = "c:/temp/ReadPdf.pdf";

  public static void main(String[] args) throws DocumentException,
      IOException {
    Document document = new Document();

    PdfWriter writer = PdfWriter.getInstance(document,
        new FileOutputStream(OUTPUTFILE));
    document.open();
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages();
    PdfImportedPage page;
    // Go through all pages
    for (int i = 1; i <= n; i++) {
      // Only page number 2 will be included
      if (i == 2) {
        page = writer.getImportedPage(reader, i);
        Image instance = Image.getInstance(page);
        document.add(instance);
      }
    }
    document.close();

  }

} 

6. Thank you

Please help me to support this article:

Flattr this

7. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

8. Links and Literature

8.1. Source Code

Source Code of Examples

8.2. iText Resources

iText Homepage

http://itextdocs.lowagie.com/tutorial/ Tutorial from iText homepage, lots of specific examples

8.3. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值