我们先来了解一下这个第三方库:iText
,对,没错,它就是我们今天的主角。
iText
是著名的开放源码站点sourceforge
一个项目,是用于生成PDF
文档的一个java
类库,通过iText
不仅可以生成PDF
或rtf
的文档,而且还可以将XML
、Html
文件转化为PDF
文件。
iText
目前有两套版本,分别是iText5
和iText7
。iText5
应该是网上用的比较多的一个版本。iText5
因为是很多开发者参与贡献代码,因此在一些规范和设计上存在不合理的地方。iText7
是后来官方针对iText5
的重构,两个版本差别还是挺大的。不过在实际使用中,一般用到的都比较简单的 API,所以不用特别拘泥于使用哪个版本。
<dependencies>
<!-- pdf:start -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.11</version>
</dependency>
<!-- 支持中文 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 支持css样式渲染 -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.16</version>
</dependency>
<!-- 转换html为标准xhtml包 -->
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>r938</version>
</dependency>
<!-- pdf:end -->
</dependencies>
2.2、简单实现
我们先来一个hello world
,代码如下:
public class CreatePDFMainTest {
public static void main(String[] args) throws Exception {
Document document = new Document(PageSize.A4);
//第二步,创建Writer实例
PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
//创建中文字体
BaseFont bfchinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfchinese, 12, Font.NORMAL);
//第三步,打开文档
document.open();
//第四步,写入内容
Paragraph paragraph = new Paragraph("hello world", fontChinese);
document.add(paragraph);
//第五步,关闭文档
document.close();
}
}