1、pom依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>core-renderer</artifactId>
<version>R8</version>
</dependency>
2、转换工具类
import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
/**
* Created by roy on 2017/12/19.
*/
public class PDFUtil {
/**
* 生成 PDF 文件
* @param out 输出流
* @param html HTML字符串
* @throws IOException IO异常
* @throws DocumentException Document异常
*/
public static void createPDF(OutputStream out, String html) throws IOException, DocumentException {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
if (System.getProperty("os.name").contains("Window")) {
fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} else {
fontResolver.addFont("/usr/share/fonts/win/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
renderer.layout();
renderer.createPDF(out);
}
public static void main(String[] args) throws IOException, DocumentException {
File file = new File("/app/data/test.pdf");
FileOutputStream outputStream = new FileOutputStream(file);
String html =
"<html>\n" +
"<head>\n" +
"<style type=\"text/css\">\n" +
"body {\n" +
"\tfont-family: SimSun;\n" +
"}\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<img src=\"http://upload-images.jianshu.io/upload_images/3424642-455a7e76316807e6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700\"></img>\n" +
"\n" +
"<table border=\"1\">\n" +
"<tr>\n" +
"<td>row 1, cell 1</td>\n" +
"<td>row 1, cell 2</td>\n" +
"</tr>\n" +
"<tr>\n" +
"<td>哈哈哈</td>\n" +
"<td>row 2, cell 2</td>\n" +
"</tr>\n" +
"</table>\n" +
"</body>\n" +
"</html>\n";
createPDF(outputStream,html);
}
3、备注
xhtmlrenderer只能处理静态化的html。由于xhtmlrenderer对html的检查很严格,必须使用闭合标签,即"<img></img>"或者"<img/>"这种才是可识别的。而且如果是复杂一点的html,最外层必须有"<html></html>"标签才可以。