maven:
<dependencies>
<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>
</dependencies>
java:
import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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("D://test.pdf");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
String html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" +
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n" +
"\n" +
"<head>\n" +
"\t<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n" +
"\t<title>Title</title>\n" +
"\t<style type=\"text/css\">\n" +
"\t\t.red{\n" +
"\t\t\tcolor:red;\n" +
"\t\t\tfont-size:30px;\n" +
"\t\t}\n" +
"\t</style>\n" +
"</head>\n" +
"\n" +
"<body style = \"font-family: SimSun\" > \n" +
"\t<p class=\"red\">123123</p>\n" +
"\t<p style=\"margin-left:300px;font-family: SimSun;\">22尊敬的用户</p>\n" +
"</body>\n" +
"\n" +
"</html>";
createPDF(outputStream, html);
}
}
xhtmlrenderer只能处理静态化的html。由于xhtmlrenderer对html的检查很严格,必须使用闭合标签,即<img></img>
或者<img/>
这种才是可识别的。而且如果是复杂一点的html,最外层必须有<html></html>
标签才可以。