Java实现HTML代码生成PDF文档

来源:互联网 发布:myeclipse mac 破解版 编辑:程序博客网 时间:2024/05/20 05:23

转:http://blog.csdn.net/zdtwyjp/archive/2010/07/27/5769353.aspx

 

1、IText实现html2pdf,速度快,纠错能力差,支持中文(要求HTML使用unicode编码),但中支持一种中文字体,开源。

2、Flying Sauser实现html2pdf,纠错能力差,支持多种中文字体(部分样式不能识别),开源。

3、PD4ML实现html2pdf,速度快,纠错能力强,支持多种中文字体,商业。

(一)IText

         官网:http://www.itextpdf.com/

         测试案例:TestIText.java

         依赖jar包:iText-2.0.8.jar、iTextAsian.jar(支持中文)

         下面只是一个小的测试案例,如果项目中使用到了该组件可以参考API完成项目组中相应的功能!

         

view plaincopy to clipboardprint?
  1. import java.io.FileOutputStream;   
  2. import java.io.FileReader;   
  3. import java.util.ArrayList;   
  4. import com.lowagie.text.Document;   
  5. import com.lowagie.text.Element;   
  6. import com.lowagie.text.Font;   
  7. import com.lowagie.text.PageSize;   
  8. import com.lowagie.text.Paragraph;   
  9. import com.lowagie.text.html.simpleparser.HTMLWorker;   
  10. import com.lowagie.text.html.simpleparser.StyleSheet;   
  11. import com.lowagie.text.pdf.BaseFont;   
  12. import com.lowagie.text.pdf.PdfWriter;   
  13. public class TestIText{   
  14.     public static void main(String[] args) {   
  15.         TestIText ih = new TestIText();   
  16.         ih.htmlCodeComeFromFile("D://Test//iText.html""D://Test//iText_1.pdf");   
  17.         ih.htmlCodeComeString("Hello中文""D://Test//iText_2.pdf");   
  18.     }   
  19.        
  20.     public void htmlCodeComeFromFile(String filePath, String pdfPath) {   
  21.         Document document = new Document();   
  22.         try {   
  23.             StyleSheet st = new StyleSheet();   
  24.             st.loadTagStyle("body""leading""16,0");   
  25.             PdfWriter.getInstance(document, new FileOutputStream(pdfPath));   
  26.             document.open();   
  27.             ArrayList p = HTMLWorker.parseToList(new FileReader(filePath), st);   
  28.             for(int k = 0; k < p.size(); ++k) {   
  29.                 document.add((Element)p.get(k));   
  30.             }   
  31.             document.close();   
  32.             System.out.println("文档创建成功");   
  33.         }catch(Exception e) {   
  34.             e.printStackTrace();   
  35.         }   
  36.     }   
  37.   
  38.     public void htmlCodeComeString(String htmlCode, String pdfPath) {   
  39.         Document doc = new Document(PageSize.A4);   
  40.         try {   
  41.             PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));   
  42.             doc.open();   
  43.             // 解决中文问题   
  44.             BaseFont bfChinese = BaseFont.createFont("STSong-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);   
  45.             Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);   
  46.             Paragraph t = new Paragraph(htmlCode, FontChinese);   
  47.             doc.add(t);   
  48.             doc.close();   
  49.             System.out.println("文档创建成功");   
  50.         }catch(Exception e) {   
  51.             e.printStackTrace();   
  52.         }   
  53.     }   
  54. }  

 

 

 (二)Flying Sauser

         项目主页:https://xhtmlrenderer.dev.java.net/

         依赖jar包:iText-2.0.8.jar、iTextAsian.jar、core-renderer.jar

         默认情况下,core-renderer.jar对中文是不能进行换行的,如果想解决换行问题可以去http://bettereveryday.javaeye.com/blog/611561下载一个jar包,该包对源代码做了稍加修改.

        下面只是一个小的测试案例,如果项目中使用到了该组件可以参考API完成项目组中相应的功能!

        

view plaincopy to clipboardprint?
  1. import java.io.File;   
  2. import java.io.FileOutputStream;   
  3. import java.io.OutputStream;   
  4.   
  5. import org.xhtmlrenderer.pdf.ITextFontResolver;   
  6. import org.xhtmlrenderer.pdf.ITextRenderer;   
  7.   
  8. import com.lowagie.text.pdf.BaseFont;   
  9.   
  10. public class TestFlyingSauser {   
  11.     public static void main(String[] args) throws Exception {   
  12.         demo_1();   
  13.         demo_2();   
  14.     }   
  15.   
  16.     // 不支持中文   
  17.     public static void demo_1() throws Exception {   
  18.         String inputFile = "D:/Test/flying.html";   
  19.         String url = new File(inputFile).toURI().toURL().toString();   
  20.         String outputFile = "D:/Test/flying.pdf";   
  21.         OutputStream os = new FileOutputStream(outputFile);   
  22.         ITextRenderer renderer = new ITextRenderer();   
  23.         renderer.setDocument(url);   
  24.         renderer.layout();   
  25.         renderer.createPDF(os);   
  26.         os.close();   
  27.     }   
  28.   
  29.     // 支持中文   
  30.     public static void demo_2() throws Exception {   
  31.         String outputFile = "D:/Test/demo_3.pdf";   
  32.         OutputStream os = new FileOutputStream(outputFile);   
  33.         ITextRenderer renderer = new ITextRenderer();   
  34.         ITextFontResolver fontResolver = renderer.getFontResolver();   
  35.         fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);   
  36.         StringBuffer html = new StringBuffer();   
  37.         // DOCTYPE 必需写否则类似于 这样的字符解析会出现错误   
  38.         html.append("<!DOCTYPE html PUBLIC /"-//W3C//DTD XHTML 1.0 Transitional//EN/" /"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd/">");   
  39.         html.append("<html xmlns=/"http://www.w3.org/1999/xhtml/">").append("<head>")   
  40.             .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")   
  41.             .append("<mce:style type=/"text/css/"><!--   
  42. body {font-family: SimSun;}   
  43. --></mce:style><style type=/"text/css/" mce_bogus="1">body {font-family: SimSun;}</style>")   
  44.             .append("</head>")   
  45.             .append("<body>");   
  46.         html.append("<div>支持中文!</div>");   
  47.         html.append("</body></html>");   
  48.         renderer.setDocumentFromString(html.toString());   
  49.         // 解决图片的相对路径问题   
  50.         // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");   
  51.         renderer.layout();   
  52.         renderer.createPDF(os);   
  53.         os.close();   
  54.     }   
  55. }  

 

        

         http://bettereveryday.javaeye.com/blog/611561

         参考资料:http://yongboy.javaeye.com/blog/510976

                        http://www.51itsns.com/sns/space.php?uid=4&do=blog&id=582

       

         关于Flying Sauser的一篇非常不错的文章:http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

(三)PD4ML

        官网下载:http://pd4ml.com/downloads.htm

        依赖jar包:pd4ml_demo.jar、pd4ml__css2.jar、fonts.jar

       下面只是一个小的测试案例,如果项目中使用到了该组件可以参考API完成项目组中相应的功能!

      

view plaincopy to clipboardprint?
  1. import java.awt.Insets;   
  2. import java.io.File;   
  3. import java.io.FileOutputStream;   
  4. import java.io.StringReader;   
  5.   
  6. import org.zefer.pd4ml.PD4Constants;   
  7. import org.zefer.pd4ml.PD4ML;   
  8.   
  9. public class Converter {   
  10.     public static void main(String[] args) throws Exception {   
  11.         Converter converter = new Converter();   
  12.         converter.generatePDF_2(new File("D:/Test/demo_ch_pd4ml_a.pdf"), "D:/Test/a.htm");   
  13.         File pdfFile = new File("D:/Test/demo_ch_pd4ml.pdf");   
  14.         StringBuffer html = new StringBuffer();   
  15.         html.append("<html>")   
  16.             .append("<head>")   
  17.             .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")   
  18.             .append("</head>")   
  19.             .append("<body>")   
  20.             .append("<font face=/"KaiTi_GB2312/">")   
  21.             .append("<font color='red' size=22>显示中文</font>")   
  22.             .append("</font>")   
  23.             .append("</body></html>");   
  24.         StringReader strReader = new StringReader(html.toString());   
  25.         converter.generatePDF_1(pdfFile, strReader);   
  26.     }   
  27.     // 手动构造HTML代码   
  28.     public void generatePDF_1(File outputPDFFile, StringReader strReader) throws Exception {   
  29.         FileOutputStream fos = new FileOutputStream(outputPDFFile);   
  30.         PD4ML pd4ml = new PD4ML();   
  31.         pd4ml.setPageInsets(new Insets(20101010));   
  32.         pd4ml.setHtmlWidth(950);   
  33.         pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));   
  34.         pd4ml.useTTF("java:fonts"true);   
  35.         pd4ml.setDefaultTTFs("KaiTi_GB2312""KaiTi_GB2312""KaiTi_GB2312");   
  36.         pd4ml.enableDebugInfo();   
  37.         pd4ml.render(strReader, fos);   
  38.     }   
  39.   
  40.     // HTML代码来自于HTML文件   
  41.     public void generatePDF_2(File outputPDFFile, String inputHTMLFileName) throws Exception {   
  42.         FileOutputStream fos = new FileOutputStream(outputPDFFile);   
  43.         PD4ML pd4ml = new PD4ML();   
  44.         pd4ml.setPageInsets(new Insets(20101010));   
  45.         pd4ml.setHtmlWidth(950);   
  46.         pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));   
  47.         pd4ml.useTTF("java:fonts"true);   
  48.         pd4ml.setDefaultTTFs("KaiTi_GB2312""KaiTi_GB2312""KaiTi_GB2312");   
  49.         pd4ml.enableDebugInfo();   
  50.         pd4ml.render("file:" + inputHTMLFileName, fos);   
  51.     }   
  52. }  

 

      参考资料:

       http://www.pd4ml.com/examples.htm

       http://www.pd4ml.com/api/index.html

       http://pd4ml.com/reference.htm#7.1

       http://pd4ml.com/support/html-pdf-faq-f1/double-byte-support-t195.html

       http://pd4ml.com/support/pd4ml-html-css-pdf-tips-tricks-f7/ttf-embedding-t42.html

      生成PDF文档的方案大致就这些了,希望能够给大家带来帮助!如果上面的三种方案都还不能满足项目组的需求哪就只有去买商业软件了。