search
HomeWeb Front-endHTML TutorialJava实现HTML代码生成PDF文档_html/css_WEB-ITnose

标签: 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推荐
  • —软件人才免语言低担保 赴美带薪读研!—
Statement
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
The Versatility of HTML: Applications and Use CasesThe Versatility of HTML: Applications and Use CasesApr 30, 2025 am 12:03 AM

HTML is not only the skeleton of web pages, but is more widely used in many fields: 1. In web page development, HTML defines the page structure and combines CSS and JavaScript to achieve rich interfaces. 2. In mobile application development, HTML5 supports offline storage and geolocation functions. 3. In emails and newsletters, HTML improves the format and multimedia effects of emails. 4. In game development, HTML5's Canvas API is used to create 2D and 3D games.

What is the root tag in an HTML document?What is the root tag in an HTML document?Apr 29, 2025 am 12:10 AM

TheroottaginanHTMLdocumentis.Itservesasthetop-levelelementthatencapsulatesallothercontent,ensuringproperdocumentstructureandbrowserparsing.

Are the HTML tags and elements the same thing?Are the HTML tags and elements the same thing?Apr 28, 2025 pm 05:44 PM

The article explains that HTML tags are syntax markers used to define elements, while elements are complete units including tags and content. They work together to structure webpages.Character count: 159

What is the significance of <head> and <body> tag in HTML?What is the significance of <head> and <body> tag in HTML?Apr 28, 2025 pm 05:43 PM

The article discusses the roles of <head> and <body> tags in HTML, their impact on user experience, and SEO implications. Proper structuring enhances website functionality and search engine optimization.

What is the difference between <strong>, <b> tags and <em>, <i> tags?What is the difference between <strong>, <b> tags and <em>, <i> tags?Apr 28, 2025 pm 05:42 PM

The article discusses the differences between HTML tags , , , and , focusing on their semantic vs. presentational uses and their impact on SEO and accessibility.

Please explain how to indicate the character set being used by a document in HTML?Please explain how to indicate the character set being used by a document in HTML?Apr 28, 2025 pm 05:41 PM

Article discusses specifying character encoding in HTML, focusing on UTF-8. Main issue: ensuring correct display of text, preventing garbled characters, and enhancing SEO and accessibility.

What are the various formatting tags in HTML?What are the various formatting tags in HTML?Apr 28, 2025 pm 05:39 PM

The article discusses various HTML formatting tags used for structuring and styling web content, emphasizing their effects on text appearance and the importance of semantic tags for accessibility and SEO.

What is the difference between the 'id' attribute and the 'class' attribute of HTML elements?What is the difference between the 'id' attribute and the 'class' attribute of HTML elements?Apr 28, 2025 pm 05:39 PM

The article discusses the differences between HTML's 'id' and 'class' attributes, focusing on their uniqueness, purpose, CSS syntax, and specificity. It explains how their use impacts webpage styling and functionality, and provides best practices for

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.