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
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 <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

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 <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

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 <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> 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 <iframe> tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

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.

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software