1、IText实现html2pdf,速度快,纠错能力差,支持中文(要求HTML使用unicode编码),但中支持一种中文字体,开源。
2、Flying Sauser实现html2pdf,纠错能力差,支持多种中文字体(部分样式不能识别),开源。
3、PD4ML实现html2pdf,速度快,纠错能力强,支持多种中文字体,商业。
这里只介绍 PD4ML
PD4ML
官网下载:http://pd4ml.com/downloads.htm
依赖jar包:pd4ml_demo.jar、pd4ml__css2.jar、fonts.jar
下面只是一个小的测试案例,如果项目中使用到了该组件可以参考API完成项目组中相应的功能!
- import java.awt.Insets;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.StringReader;
-
- import org.zefer.pd4ml.PD4Constants;
- import org.zefer.pd4ml.PD4ML;
-
- public class Converter {
- public static void main(String[] args) throws Exception {
- Converter converter = new Converter();
- converter.generatePDF_2(new File("D:/Test/demo_ch_pd4ml_a.pdf"), "D:/Test/a.htm");
- File pdfFile = new File("D:/Test/demo_ch_pd4ml.pdf");
- StringBuffer html = new StringBuffer();
- html.append("<html>")
- .append("<head>")
- .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")
- .append("</head>")
- .append("<body>")
- .append("<font face=/"KaiTi_GB2312/">")
- .append("<font color='red' size=22>显示中文</font>")
- .append("</font>")
- .append("</body></html>");
- StringReader strReader = new StringReader(html.toString());
- converter.generatePDF_1(pdfFile, strReader);
- }
-
- public void generatePDF_1(File outputPDFFile, StringReader strReader) throws Exception {
- FileOutputStream fos = new FileOutputStream(outputPDFFile);
- PD4ML pd4ml = new PD4ML();
- pd4ml.setPageInsets(new Insets(20, 10, 10, 10));
- pd4ml.setHtmlWidth(950);
- pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
- pd4ml.useTTF("java:fonts", true);
- pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312");
- pd4ml.enableDebugInfo();
- pd4ml.render(strReader, fos);
- }
-
-
- public void generatePDF_2(File outputPDFFile, String inputHTMLFileName) throws Exception {
- FileOutputStream fos = new FileOutputStream(outputPDFFile);
- PD4ML pd4ml = new PD4ML();
- pd4ml.setPageInsets(new Insets(20, 10, 10, 10));
- pd4ml.setHtmlWidth(950);
- pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
- pd4ml.useTTF("java:fonts", true);
- pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312");
- pd4ml.enableDebugInfo();
- pd4ml.render("file:" + inputHTMLFileName, fos);
- }