Itext7使用总结

  • 最近由于工作需要,需要实现内容动态生成为pdf文档,使用itext7是因为官方有详细说明文档及例子并支持免费使用,附上官网地址 http://itextpdf.com/ 总结包括如何从0到1使用itext7,解决itext7支持中文、图片悬浮在内容上(类似合同公章xiaog)、实现直接将pdf流传输到远端服务生成pdf,而不是先从本地生成pdf,再读取本地文件传输至服务器端。

    1. 支持maven配置添加itext7开发所需jar包 详细可见官网 http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/installing-itext-7 成功运行maven命令就会把相应的jar下载到本地
 <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>barcodesartifactId>
    <version>7.0.0version>
    
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>font-asianartifactId>
    <version>7.0.0version>
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>formsartifactId>
    <version>7.0.0version>
    
  dependency>
  <dependency>
      <groupId>com.itextpdfgroupId>
      <artifactId>hyphartifactId>
      <version>7.0.0version>
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>ioartifactId>
    <version>7.0.0version>
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>kernelartifactId>
    <version>7.0.0version>
    
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>layoutartifactId>
    <version>7.0.0version>
    
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>pdfaartifactId>
    <version>7.0.0version>
    
  dependency>
  <dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>signartifactId>
    <version>7.0.0version>
    
  dependency>

<distributionManagement>
  <repository>
    <id>itextid>
    <name>iText Repository - releasesname>
    <url>https://repo.itextsupport.com/releasesurl>
  repository>
distributionManagement>

2.itext7默认是不支持中文,pdf中的中文字体将不进行显示,需要进行字体的设置,大家使用的使用会发现很多元素都有 setFont()方法,只要元素中涉及到了中文内容都需要如以下例子设置字体,字体能生效是由于上文中添加了font-asian的jar包,
虽然可以支持中文,但是缺点也很明显,字体样式单一,英文内容不美观,如果有更好的方法请及时回复我。

Paragraph cn = new Paragraph("中文内容");
PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", false);
cn.setFont(font);

3.实现生成的pdf图片悬浮于内容上,主要有两种方式,类似于css中图片的相对位置和绝对位置来实现图片的悬浮。
图片使用相对位置移动,缺点虽然图片悬浮在pdf内容之上,但是图片原来占用的空间依旧存在,会变成空白行

Image img = new Image(ImageDataFactory.create("src/main/resources/img/magic.png"));
img.setRelativePosition(80, -120, 100, 0);//左、上、右、下 

图片使用绝对位置,图片的位置固定不能根据内容动态移动

Image img = new Image(ImageDataFactory.create("src/main/resources/img/magic.png"));
img.setFixedPosition(80, 560);//有传页数参数的方法

4.由于pdf文档最终要传递至远端服务器,开始版本是先用itext7生成一份pdf到本地,再拿到本地的pdf路径读取内容并上传至服务器,为了加快上传效率不进行生成本地pdf直接拿到itext7的写入流传输至服务器生成pdf。
解决方案如下:

ByteArrayOutputStream bao = new ByteArrayOutputStream();//新建一个输出流
PdfWriter writer = new PdfWriter(bao);//pdfWriter 使用传递输出流为参数的构造函数

ByteArrayInputStream swapStream = new ByteArrayInputStream(bao.toByteArray());//将输出流转换为输入流
ossClient.uploadWithInputStream(OssConfig.BUCKET_AD, path, swapStream);//传递输入流至服务器生成pdf

itext7结构还是很庞大,我只了解了工作相关的一些知识,以上是我根据实际情况想出的解决方案,各位有更好的方法或方案记得一定要@我。

你可能感兴趣的:(经验总结)