maven依赖如下:

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.3</version>
        </dependency>

输出中文,还要引入下面itext-asian.jar包:

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

设置pdf文件密码,还要引入下面bcprov-jdk15on.jar包:

<dependency>
     <groupId>org.bouncycastle</groupId>
     <artifactId>bcprov-jdk15on</artifactId>
     <version>1.54</version>
</dependency>

iText常用类

  1. com.itextpdf.text.Document:这是iText库中最常用的类,它代表了一个pdf实例。如果你需要从零开始生成一个PDF文件,你需要使用这个Document类。首先创建(new)该实例,然后打开(open)它,并添加(add)内容,最后关闭(close)该实例,即可生成一个pdf文件。
  2. com.itextpdf.text.Paragraph:表示一个缩进的文本段落,在段落中,你可以设置对齐方式,缩进,段落前后间隔等
  3. com.itextpdf.text.Chapter:表示PDF的一个章节,他通过一个Paragraph类型的标题和整形章数创建
  4. com.itextpdf.text.Font:这个类包含了所有规范好的字体,包括family of font,大小,样式和颜色,所有这些字体都被声明为静态常量
  5. com.itextpdf.text.List:表示一个列表;
  6. com.itextpdf.text.Anchor:表示一个锚,类似于HTML页面的链接。
  7. com.itextpdf.text.pdf.PdfWriter:当这个PdfWriter被添加到PdfDocument后,所有添加到Document的内容将会写入到与文件或网络关联的输出流中。
    com.itextpdf.text.pdf.PdfReader:用于读取PDF文件;

PDF中创建表格

public static void main(String[] args) throws DocumentException, FileNotFoundException {
         //创建文件
         Document document = new Document();
         //建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test4.pdf"));
         //打开文件
         document.open();
         //添加内容
         document.add(new Paragraph("HD content here"));
      
         // 3列的表.
         PdfPTable table = new PdfPTable(3); 
         table.setWidthPercentage(100); // 宽度100%填充
         table.setSpacingBefore(10f); // 前间距
         table.setSpacingAfter(10f); // 后间距
 
         List<PdfPRow> listRow = table.getRows();
         //设置列宽
         float[] columnWidths = { 1f, 2f, 3f };
         table.setWidths(columnWidths);
         
         //行1
         PdfPCell cells1[]= new PdfPCell[3];
         PdfPRow row1 = new PdfPRow(cells1);
        
         //单元格
         cells1[0] = new PdfPCell(new Paragraph("111"));//单元格内容
         cells1[0].setBorderColor(BaseColor.BLUE);//边框验证
         cells1[0].setPaddingLeft(20);//左填充20
         cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
         cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
 
         cells1[1] = new PdfPCell(new Paragraph("222"));
         cells1[2] = new PdfPCell(new Paragraph("333"));
         
         //行2
         PdfPCell cells2[]= new PdfPCell[3];
         PdfPRow row2 = new PdfPRow(cells2);
         cells2[0] = new PdfPCell(new Paragraph("444"));
 
         //把第一行添加到集合
         listRow.add(row1);
         listRow.add(row2);
         //把表格添加到文件中
         document.add(table);
         
         //关闭文档
         document.close();
         //关闭书写器
         writer.close();
     }

android iText根据view生成pdf_List

给PDF文件设置文件属性

public static void main(String[] args) throws FileNotFoundException, DocumentException {
         
         //创建文件
         Document document = new Document();
         //建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test2.pdf"));
         //打开文件
         document.open();
         //添加内容
         document.add(new Paragraph("Some content here"));
      
         //设置属性
         //标题
         document.addTitle("this is a title");
         //作者
         document.addAuthor("H__D");
         //主题
         document.addSubject("this is subject");
         //关键字
         document.addKeywords("Keywords");
         //创建时间
         document.addCreationDate();
         //应用程序
         document.addCreator("hd.com");
         
         //关闭文档
         document.close();
         //关闭书写器
         writer.close();
     }

android iText根据view生成pdf_创建文件_02

PDF中添加图片

public static void main(String[] args) throws DocumentException, IOException {
         
         //创建文件
         Document document = new Document();
         //建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test3.pdf"));
         //打开文件
         document.open();
         //添加内容
         document.add(new Paragraph("HD content here"));
      
         //图片1
         Image image1 = Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");
         //设置图片位置的x轴和y周
         image1.setAbsolutePosition(100f, 550f);
         //设置图片的宽度和高度
         image1.scaleAbsolute(200, 200);
         //将图片1添加到pdf文件中
         document.add(image1);
      
         //图片2
         Image image2 = Image.getInstance(new URL(""));
         //将图片2添加到pdf文件中
         document.add(image2);
         
         //关闭文档
         document.close();
         //关闭书写器
         writer.close();
     }

PDF中创建列表

public static void main(String[] args) throws DocumentException, FileNotFoundException {
         //创建文件
         Document document = new Document();
         //建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test5.pdf"));
         //打开文件
         document.open();
         //添加内容
         document.add(new Paragraph("HD content here"));
      
         //添加有序列表
         List orderedList = new List(List.ORDERED);
         orderedList.add(new ListItem("Item one"));
         orderedList.add(new ListItem("Item two"));
         orderedList.add(new ListItem("Item three"));
         document.add(orderedList);
 
         //关闭文档
         document.close();
         //关闭书写器
         writer.close();
     }

android iText根据view生成pdf_java_03

PDF中设置样式/格式化输出,输出中文内容,必须引入itext-asian.jar

public static void main(String[] args) throws DocumentException, IOException {
         //创建文件
         Document document = new Document();
         //建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test6.pdf"));
         //打开文件
         document.open();
         
         //中文字体,解决中文不能显示问题
         BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
         
         //蓝色字体
         Font blueFont = new Font(bfChinese,12, Font.NORMAL);
         blueFont.setColor(BaseColor.BLUE);
         //段落文本
         Paragraph paragraphBlue = new Paragraph("paragraphOne blue front", blueFont);
         document.add(paragraphBlue);
      
         //绿色字体
         Font greenFont = new Font(bfChinese,12, Font.NORMAL);
         greenFont.setColor(BaseColor.GREEN);
         //创建章节
         Paragraph chapterTitle = new Paragraph("段落标题xxxx", greenFont);
         Chapter chapter1 = new Chapter(chapterTitle, 1);
         chapter1.setNumberDepth(0);
        
         Paragraph sectionTitle = new Paragraph("部分标题", greenFont);
         Section section1 = chapter1.addSection(sectionTitle);
      
         Paragraph sectionContent = new Paragraph("部分内容", blueFont);
         section1.add(sectionContent);
         
         //将章节添加到文章中
         document.add(chapter1);
         
         //关闭文档
         document.close();
         //关闭书写器
         writer.close();
     }

android iText根据view生成pdf_创建文件_04

给PDF文件设置密码,需要引入bcprov-jdk15on.jar包

public static void main(String[] args) throws DocumentException, IOException {
         // 创建文件
         Document document = new Document();
         // 建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test8.pdf"));
 
         //用户密码
         String userPassword = "123456";
         //拥有者密码
         String ownerPassword = "hd";
         writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING,
                 PdfWriter.ENCRYPTION_AES_128);
 
         // 打开文件
         document.open();
         
         //添加内容
         document.add(new Paragraph("password !!!!"));
 
         // 关闭文档
         document.close();
         // 关闭书写器
         writer.close();
     }

android iText根据view生成pdf_List_05

给PDF文件设置权限

public static void main(String[] args) throws DocumentException, IOException {
         // 创建文件
         Document document = new Document();
         // 建立一个书写器
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test9.pdf"));
 
         // 只读权限
         writer.setEncryption("".getBytes(), "".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
 
         // 打开文件
         document.open();
 
         // 添加内容
         document.add(new Paragraph("password !!!!"));
 
         // 关闭文档
         document.close();
         // 关闭书写器
         writer.close();
     }

读取/修改已有的PDF文件

public static void main(String[] args) throws DocumentException, IOException {
         
         //读取pdf文件
         PdfReader pdfReader = new PdfReader("C:/Users/H__D/Desktop/test1.pdf");
      
         //修改器
         PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("C:/Users/H__D/Desktop/test10.pdf"));
      
         Image image = Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");
         image.scaleAbsolute(50, 50);
         image.setAbsolutePosition(0, 700);
      
         for(int i=1; i<= pdfReader.getNumberOfPages(); i++)
         {
             PdfContentByte content = pdfStamper.getUnderContent(i);
             content.addImage(image);
         }
      
         pdfStamper.close();
     }

pdf工具类

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPRow;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;

/**
 * @author sxyuser
 * @description pdf导出工具类
 * @date 2022/5/11 9:22:31
 */
@Slf4j
public class PdfUtil {

  private PdfUtil() {}

  // 生成pdf文件
  public static void createPdf(File filePath, PdfPTable table)
      throws DocumentException, FileNotFoundException {
    log.error("filePath----------{}", filePath.getPath());
    // 1.创建一个文档实例 设置文档纸张为A4
    Document document = new Document(PageSize.A4);
    // 2.创建PdfWriter对象,设置pdf生成路径
    PdfWriter instance = PdfWriter.getInstance(document, new FileOutputStream(filePath));
    // 3.打开文档进行我们需要的操作
    document.open();

    document.add(table);

    // 5.关闭文档
    document.close();
    instance.close();
  }
  /**
   * 生成表格的一行
   *
   * @param cell1 第一列
   * @param cell2 第二列
   * @return 行数据
   */
  public static PdfPRow pdfRow(PdfPCell cell1, PdfPCell cell2) {
    PdfPCell[] pdfCell = new PdfPCell[2];
    if (cell2 == null) {
      // 合并列
      cell1.setColspan(2);
    }
    // 将数据放入第一列
    pdfCell[0] = cell1;
    // 将数据放入第二列
    pdfCell[1] = cell2;
    return new PdfPRow(pdfCell);
  }

  /**
   * 生成表格
   *
   * @param columns 表格的列数
   * @param columnWidths 列宽
   * @return 表格实例
   */
  public static PdfPTable doCreateTable(int columns, float[] columnWidths)
      throws DocumentException {
    // 1.生成一个两列的表格
    PdfPTable table = new PdfPTable(columns);
    // 表格占比100%
    table.setWidthPercentage(100);
    // 设置前后距离
    table.setSpacingBefore(20f);
    table.setSpacingAfter(20f);
    table.setWidths(columnWidths);
    return table;
  }

  /**
   * 生成一个有特性的单元格
   *
   * @param cellContent 单元格中的数据
   * @return 单元格
   */
  public static PdfPCell createSpecialCell(String cellContent) {

    BaseFont baseFont = null;
    try {
      // 设置支持中文
      baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
      log.error(e.getMessage());
    }
    // 设置字体
    Font font = new Font(baseFont, 12, Font.NORMAL);
    Paragraph phrase = new Paragraph(cellContent, font);
    PdfPCell cell = new PdfPCell(phrase);
    // 内边距:10
    cell.setPaddingLeft(10);
    // 水平居左
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    // 单元格内容垂直居中
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    return cell;
  }

  /**
   * 下载文件
   *
   * @param filePath 文件地址
   * @param response 前台响应
   */
  public static void downLoadFile(File filePath, HttpServletResponse response) {
    // 重置响应
    response.reset();
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
      log.error("downLoadFile--------{}", filePath);
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/html;chartSet=UTF-8");
      response.setContentType("application/pdf");
      response.addHeader(
          "Content-Disposition",
          "attachment;filename=" + URLEncoder.encode("模板.pdf", StandardCharsets.UTF_8));
      // 对流进行拷贝
      IOUtils.copy(bis, bos);
      // 关闭流
      response.getOutputStream().flush();
      IOUtils.closeQuietly(bis);
      IOUtils.closeQuietly(bos);
    } catch (Exception e) {
      log.error("【下载文件】下载文件失败,失败信息为{}", e.getMessage());
    }
  }

  /**
   * 递归删除目录下的所有文件及子目录下所有文件
   *
   * @param file 文件
   */
  public static void deleteFile(File file) {
    // 判断指定路径的文件或文件是否存在
    if (!file.exists()) {
      return;
    }
    // 返回当前路径下的所有文件和文件夹名称
    File[] files = file.listFiles();
    // 遍历所有文件及文件夹
    assert files != null;
    for (File f : files) {
      // 如果是文件就删除
      if (f.isFile()) {
        // 删除文件
        f.delete();
      } else {
        // 如果是目录,则调用递归方法
        deleteFile(f);
      }
    }
  }
}

工具类的使用

// 获取文件路径
    File filePath = new ClassPathResource("static/file/模板.pdf").getFile();

// 创建一个两列的表格
    PdfPTable table = doCreateTable(2, new float[] {1f, 1f});

    // 查询的集合数据,循环遍历数据
    infoArrayList.forEach(
        e -> {
          // 获得表格的行的集合
          ArrayList<PdfPRow> rows = table.getRows();
          //第一行
            rows.add(pdfRow(createSpecialCell(e.getTitle()), null));
            // 第二行
            rows.add(pdfRow(createSpecialCell(e.getChoice1()), createSpecialCell(e.getChoice2())));
          }
        });
    // 创建pdf
    PdfUtil.createPdf(filePath, table);

效果图

android iText根据view生成pdf_创建文件_06