Java中使用iText生成PDF

时间:2020-01-09 10:35:27  来源:igfitidea点击:

此教程展示了如何使用iText在Java中生成PDF。

在介绍使用iText在Java中创建PDF的示例之前,关于iText库的几点要点。

  • iText(https://itextpdf.com)带有商业和开源双重许可(AGPL)。如果我们使用的是AGPL许可证(免费),则需要在同一AGPL许可证下免费共享整个应用程序。
  • 这篇文章中显示的示例使用iText 7库,该库已被重写,并且API与iText 5不同。
  • 用于使用iText生成PDF的一些主要类如下:Document –创建自足PDF时,Document是默认的根元素。 PDFDocument –使用PDF文档的主要入口点。段落-创建一个段落,并以一段文本进行初始化。文本–文本是一段任意长度的文本。 PdfWriter –创建写入传递的输出流的PdfWriter。 PdfReader –读取PDF文档。 PdfFontFactory –此类提供有用的方法来创建准备在PdfDocument中使用的字体。表格–表格是一个布局元素,代表二维网格中的数据。

这篇文章中给出了使用iText和Java生成PDF的示例。

Maven依赖

为了使用iText 7库核心模块,我们需要将iText 7 Core作为依赖项添加到pom.xml文件。 Maven将自动从资源库下载所有必需的模块。

<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>

HelloWorld PDF Creation Java和iText示例

我们将从创建一个简单的HelloWorld PDF以及字体和文本颜色设置开始。

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://theitroad//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();
    }  
  }
}

具有样式的PDF用于内容样式

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://theitroad//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();
    }  
  }
}

使用iText将文本文件转换为PDF

在Java示例中,存在一个文本文件(Test.txt),该文件使用iText转换为PDF。

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://theitroad//result//Test.txt";
  public static final String CREATED_PDF = "F://theitroad//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();
    } 
  }
}

使用表格生成PDF

在此示例中,我们将使用Bean类Employee,雇员列表在使用Java程序的PDF表格中显示。

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://theitroad//result//Employee.pdf";
  public static void main(String[] args) {
    List<Employee> employees = new ArrayList<Employee>();
    employees.add(new Employee("Hyman", "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();
    }  
  }
}

使用iText将图像添加到PDF

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://theitroad//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();
    } 
  }
}

使用iText将列表添加到PDF

如果要将列表项添加到PDF,则可以使用List和ListItem(用于添加单个列表项)类来实现。
有一个Enum ListNumberingType,其中包含可用于为列表项编号的符号。

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://theitroad//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();
    }  
  }
}

使用iText在Web应用程序中渲染PDF

为了使用iText将PDF呈现给浏览器,需要使用ServletOutputStream作为PDFWriter的参数。我们可以从HTTPResponse获取此OutputStream。

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();
  }