Java实现HTML代码生成PDF文档_html/css_WEB-ITnose

WBOY
Release: 2016-06-21 08:48:37
Original
1292 people have browsed it

标签: java html 代码| 发表时间:2016-05-13 07:40 | 作者:hunan84229247

出处:http://www.iteye.com

http://blog.csdn.net/zdtwyjp/article/details/5769353

http://www.xuebuyuan.com/2056017.html

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完成项目组中相应的功能!

[c-sharp] view plain copy

  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 
  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完成项目组中相应的功能!

[c-sharp] view plain copy

  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("nbsp;html PUBLIC /"-//W3C//DTD XHTML 1.0 Transitional//EN/" /"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd/">");  
  39.         html.append("").append("")  
  40.             .append("")  
  41.             .append(" ")  
  42.             .append("")  
  43.             .append("");  
  44.         html.append("
    支持中文!
    ");  
  45.         html.append("");  
  46.         renderer.setDocumentFromString(html.toString());  
  47.         // 解决图片的相对路径问题  
  48.         // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");  
  49.         renderer.layout();  
  50.         renderer.createPDF(os);  
  51.         os.close();  
  52.     }  
  53. }  

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完成项目组中相应的功能!

[java] view plain copy

  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("")  
  16.             .append("")  
  17.             .append("")  
  18.             .append("")  
  19.             .append("")  
  20.             .append("")  
  21.             .append("显示中文")  
  22.             .append("")  
  23.             .append("");  
  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(20, 10, 10, 10));  
  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(20, 10, 10, 10));  
  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文档的方案大致就这些了,希望能够给大家带来帮助!如果上面的三种方案都还不能满足项目组的需求哪就只有去买商业软件了。

已有 0人发表留言,猛击->> 这里ITeye推荐
  • —软件人才免语言低担保 赴美带薪读研!—
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!