当前位置: 首页 > 编程文章 >

Java使用iText库生成PDF文档的完整示例

Java使用iText库生成PDF文档的完整示例

作者:陆景时间:2026-03-04 10:15:34浏览:357

本文介绍如何使用Java开源工具iText库生成PDF文件。首先通过CreatePDF类演示基础PDF文件的创建流程,包括初始化Document对象和设置页面大小。接着展示如何在PDF中添加表格内容,利用PdfPTable和PdfPCell构建单元格结构。最后讲解如何插入背景图片并指定文本在PDF中的具体位置,涉及BaseFont字体设置及PdfContentByte绘图层操作。

本文目录收起

iText库资源获取与基础PDF创建

获取iText库资源可访问下载页面:http://sourceforge.net/projects/itext/files/。本节将演示如何创建一个简单的PDF文件。


package console.pdf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 使用iText生成PDF文件
 */
public class CreatePDF {

  public static void main(String[] args) {
    CreatePDF p001 = new CreatePDF();

    String filename = "P001.pdf";
    p001.createPDF(filename);
  }

  public void createPDF(String filename) {
    // step 1
    Document document = new Document(PageSize.A4);
    // step 2
    try {
      PdfWriter.getInstance(document, new FileOutputStream(filename));
      
      document.addTitle("ID.NET");
      document.addAuthor("dotuian"); 
      document.addSubject("This is the subject of the PDF file."); 
      document.addKeywords("This is the keyword of the PDF file.");
      
      // step 3
      document.open();
      // step 4
      document.add(new Paragraph("Hello World!"));

      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } finally {
      // step 5
      document.close();
    }
  }

  
  
  
}

在PDF文档中构建表格结构

接下来演示如何在生成的PDF文件中添加表格元素。


package console.pdf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 使用iText生成PDF文件
 * 在PDF文件中创建表格
 */
public class TableOfPDF {

  public static void main(String[] args) {
    TableOfPDF p001 = new TableOfPDF();

    String filename = "P002.pdf";
    p001.createPDF(filename);
  }

  public void createPDF(String filename) {
    // step 1
    Document document = new Document(PageSize.A4);
    // step 2
    try {
      PdfWriter.getInstance(document, new FileOutputStream(filename));

      document.addTitle("ID.NET");
      document.addAuthor("dotuian");
      document.addSubject("This is the subject of the PDF file.");
      document.addKeywords("This is the keyword of the PDF file.");

      // step 3
      document.open();
      // step 4
      PdfPTable table = createTable1();
      document.add(table);
      
      table = createTable2();
      table.setSpacingBefore(5);
      table.setSpacingAfter(5);
      document.add(table);
      
      table = createTable3();
      document.add(table);
      
      table = createTable4();
      table.setSpacingBefore(5);
      table.setSpacingAfter(5);
      document.add(table);
      
      table = createTable5();
      document.add(table);
      
      table = createTable6();
      document.add(table);

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } finally {
      // step 5
      document.close();
    }
  }

  /**
   * Creates a table; widths are set with setWidths().
   * 
   * @return a PdfPTable
   * @throws DocumentException
   */
  public static PdfPTable createTable1() throws DocumentException {
    PdfPTable table = new PdfPTable(3);
    table.setWidthPercentage(288 / 5.23f);
    table.setWidths(new int[] { 2, 1, 1 });
    
    PdfPCell cell;
    cell = new PdfPCell(new Phrase("Table 1"));
    cell.setColspan(3);
    table.addCell(cell);
    
    cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
    cell.setRowspan(2);
    table.addCell(cell);
    table.addCell("row 1; cell 1");
    table.addCell("row 1; cell 2");
    table.addCell("row 2; cell 1");
    table.addCell("row 2; cell 2");
    return table;
  }

  /**
   * Creates a table; widths are set with setWidths().
   * 
   * @return a PdfPTable
   * @throws DocumentException
   */
  public static PdfPTable createTable2() throws DocumentException {
    PdfPTable table = new PdfPTable(3);
    table.setTotalWidth(288);
    table.setLockedWidth(true);
    table.setWidths(new float[] { 2, 1, 1 });
    PdfPCell cell;
    cell = new PdfPCell(new Phrase("Table 2"));
    cell.setColspan(3);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
    cell.setRowspan(2);
    table.addCell(cell);
    table.addCell("row 1; cell 1");
    table.addCell("row 1; cell 2");
    table.addCell("row 2; cell 1");
    table.addCell("row 2; cell 2");
    return table;
  }

  /**
   * Creates a table; widths are set in the constructor.
   * 
   * @return a PdfPTable
   * @throws DocumentException
   */
  public static PdfPTable createTable3() throws DocumentException {
    PdfPTable table = new PdfPTable(new float[] { 2, 1, 1 });
    table.setWidthPercentage(55.067f);
    PdfPCell cell;
    cell = new PdfPCell(new Phrase("Table 3"));
    cell.setColspan(3);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
    cell.setRowspan(2);
    table.addCell(cell);
    table.addCell("row 1; cell 1");
    table.addCell("row 1; cell 2");
    table.addCell("row 2; cell 1");
    table.addCell("row 2; cell 2");
    return table;
  }

  /**
   * Creates a table; widths are set with special setWidthPercentage() method.
   * 
   * @return a PdfPTable
   * @throws DocumentException
   */
  public static PdfPTable createTable4() throws DocumentException {
    PdfPTable table = new PdfPTable(3);
    Rectangle rect = new Rectangle(523, 770);
    table.setWidthPercentage(new float[] { 144, 72, 72 }, rect);
    PdfPCell cell;
    cell = new PdfPCell(new Phrase("Table 4"));
    cell.setColspan(3);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
    cell.setRowspan(2);
    table.addCell(cell);
    table.addCell("row 1; cell 1");
    table.addCell("row 1; cell 2");
    table.addCell("row 2; cell 1");
    table.addCell("row 2; cell 2");
    return table;
  }

  /**
   * Creates a table; widths are set with setTotalWidth().
   * 
   * @return a PdfPTable
   * @throws DocumentException
   */
  public static PdfPTable createTable5() throws DocumentException {
    PdfPTable table = new PdfPTable(3);
    table.setTotalWidth(new float[] { 144, 72, 72 });
    table.setLockedWidth(true);
    PdfPCell cell;
    cell = new PdfPCell(new Phrase("Table 5"));
    cell.setColspan(3);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
    cell.setRowspan(2);
    table.addCell(cell);
    table.addCell("row 1; cell 1");
    table.addCell("row 1; cell 2");
    table.addCell("row 2; cell 1");
    table.addCell("row 2; cell 2");
    return table;
  }
  
  public static PdfPTable createTable6() throws DocumentException{
    PdfPTable table = new PdfPTable(10);
    table.setTotalWidth(595);
    //table.setLockedWidth(true);
    
    
    PdfPCell cell;
    cell = new PdfPCell(new Phrase("Table 6"));
    cell.setColspan(10);
    table.addCell(cell);
    
    for (int i = 1; i < 100; i++) {
      cell = new PdfPCell(new Phrase(String.valueOf(i)));
      cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
      table.addCell(cell);
    }
    
    
//    cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
//    cell.setRowspan(2);
//    table.addCell(cell);
//    table.addCell("row 1; cell 1");
//    table.addCell("row 1; cell 2");
//    table.addCell("row 2; cell 1");
//    table.addCell("row 2; cell 2");
    return table;
  }
  
  

}

PDF图片插入与文本位置定位

进一步展示在PDF中插入图片的方法,并精确控制文本在页面上的显示位置。


package console.pdf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 使用iText生成PDF文件
 * 在PDF文件中添加背景图片,并指定文本在PDF文件中的位置
 */
public class BackgroundImageOfPDF {

  public static void main(String[] args) {
    BackgroundImageOfPDF p001 = new BackgroundImageOfPDF();

    String filename = "P003.pdf";
    p001.createPDF(filename);
  }

  public void createPDF(String filename) {
    // step 1
    Document document = new Document(PageSize.A4.rotate(),0,0,0,0);
    // step 2
    try {
      PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(filename));
      
      document.addTitle("ID.NET");
      document.addAuthor("dotuian"); 
      document.addSubject("This is the subject of the PDF file."); 
      document.addKeywords("This is the keyword of the PDF file.");
      
      // step 3
      document.open();
      // step 4
      Image image = Image.getInstance("bg.jpg");
      document.add(image);

      PdfContentByte pdfContentByte = pdfwriter.getDirectContent();
      pdfContentByte.beginText();
      BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.WINANSI,BaseFont.EMBEDDED);
      pdfContentByte.setFontAndSize(bf, 12);

      for (int i = 0; i <= 842; i = i + 50) {
        for (int j = 0; j <= 595; j = j + 20) {
          pdfContentByte.setTextMatrix(i, j);
          pdfContentByte.showText("(" + i + ":" + j + ")");
        }
      }
      
      pdfContentByte.endText();
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // step 5
      document.close();
    }
  }
}



上一篇
生成二维码的开源工具对比:Zxing、ThoughtWorks与QrCodeNet深度评测

本文对比了ZXing、ThoughtWorks和QrCodeNet三款常见开源二维码生成库。测试发现ThoughtWorks存在编码长度限制且效率虽快但适用性差;ZXing版本混淆导致性能差异大,推荐使用416KB版本;QrCodeNet在文件体积和尺寸控制上表现更优。最终建议采用代理模式封装底层库,以便灵活替换,并提供了支持Logo的完整源码下载。

下一篇
2026年十大关键开源工具:从容器化到人工智能的核心技术

Black Duck 2026年调查显示,77%的企业使用开源构建内部应用。本文盘点当年十大核心开源工具:Docker与Kubernetes主导容器化部署,Git、Java、Node.js构成开发基石,React、Angular引领前端框架,Hadoop与Spark处理大数据,TensorFlow推动AI落地。这些工具在GitHub热度及开发者调查中占据重要地位,是企业技术栈的关键组成部分。

相关文章

更多
PHP生成PDF的常用库:FPDF、DomPDF与TCPDF详解

利用PHP编码生成PDF文件曾是非常耗时的工作,早期开发者多借助FPDF类库。如今,已有多种函数库能从HTML文件直接生成PDF文档,极大简化了开发流程。本文详细介绍FPDF、DomPDF及TCPDF等主流工具的特点与适用场景。

2025.07.08 820
PHP中使用TCPDF生成PDF文档实例

本文介绍如何使用PHP库TCPDF动态创建PDF文档。TCPDF基于FPDF扩展,支持中文、HTML标签及多种图像格式。文章详细列出了从引入文件到输出PDF的五个核心步骤,并提供完整代码示例展示如何设置文档信息、页眉页脚及中文字体。此外,还对比了FPDF、HTML2PDF等其他常用PHP PDF生成工具的特性。

2026.01.27 802
PHP使用MPDF类生成PDF的方法

针对TCPDF在处理CSS背景图片时的缺陷及性能瓶颈,本文介绍采用MPDF库作为替代方案。通过访问mpdf1.com下载资源并参考官方实例与文档,开发者可高效实现HTML静态文件向PDF的转换,同时获得更快的处理速度。

2026.08.26 517
PHP生成PDF的开源库:FPDF、DomPDF与TCPDF详解

利用PHP直接编码生成PDF文件通常耗时且繁琐。早期开发者多依赖FPDF类库,而如今已有多种函数库能直接将HTML转换为PDF文档,大幅简化了工作流程。本文介绍FPDF、DomPDF和TCPDF等主流开源方案,分析其从纯代码生成到基于CSS渲染的不同技术路径及各自特性。

2026.06.06 406

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。