Home Web Front-end HTML Tutorial Java实现HTML代码生成PDF文档_html/css_WEB-ITnose

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

Jun 21, 2016 am 08:48 AM

标签: 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 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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

See all articles