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、轉(zhuǎn)換工具類
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只能處理靜態(tài)化的html。由于xhtmlrenderer對html的檢查很嚴格,必須使用閉合標簽,即"<img></img>"或者"<img/>"這種才是可識別的。而且如果是復(fù)雜一點的html,最外層必須有"<html></html>"標簽才可以。