依赖
<!-- 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 -->
使用示例
1、简单使用
package com.pengshiyu; import com.itextpdf.text.Document; 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.PdfWriter; import java.io.FileOutputStream; /** * Hello world! */ public class PdfDemo { public static void main(String[] args) throws Exception { // 新建文档 Document document = new Document(PageSize.A4); // 如果输出中文,需要设置中文字体 BaseFont chineseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font = new Font(chineseFont, 12, Font.NORMAL); PdfWriter.getInstance(document, new FileOutputStream("hello.pdf")); // 打开文档 document.open(); // 写入内容 Paragraph paragraph = new Paragraph("hello world 你好世界", font); document.add(paragraph); // 关闭文档 document.close(); } }