Java实现HTML代码生成PDF文档

转载自   Java实现HTML代码生成PDF文档

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

import java.io.FileOutputStream;  
import java.io.FileReader;  
import java.util.ArrayList;  
import com.lowagie.text.Document;  
import com.lowagie.text.Element;  
import com.lowagie.text.Font;  
import com.lowagie.text.PageSize;  
import com.lowagie.text.Paragraph;  
import com.lowagie.text.html.simpleparser.HTMLWorker;  
import com.lowagie.text.html.simpleparser.StyleSheet;  
import com.lowagie.text.pdf.BaseFont;  
import com.lowagie.text.pdf.PdfWriter;  
public class TestIText{  public static void main(String[] args) {  TestIText ih = new TestIText();  ih.htmlCodeComeFromFile("D://Test//iText.html", "D://Test//iText_1.pdf");  ih.htmlCodeComeString("Hello中文", "D://Test//iText_2.pdf");  }  public void htmlCodeComeFromFile(String filePath, String pdfPath) {  Document document = new Document();  try {  StyleSheet st = new StyleSheet();  st.loadTagStyle("body", "leading", "16,0");  PdfWriter.getInstance(document, new FileOutputStream(pdfPath));  document.open();  ArrayList p = HTMLWorker.parseToList(new FileReader(filePath), st);  for(int k = 0; k < p.size(); ++k) {  document.add((Element)p.get(k));  }  document.close();  System.out.println("文档创建成功");  }catch(Exception e) {  e.printStackTrace();  }  }  public void htmlCodeComeString(String htmlCode, String pdfPath) {  Document doc = new Document(PageSize.A4);  try {  PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));  doc.open();  // 解决中文问题  BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);  Paragraph t = new Paragraph(htmlCode, FontChinese);  doc.add(t);  doc.close();  System.out.println("文档创建成功");  }catch(Exception e) {  e.printStackTrace();  }  }  
}  

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

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStream;  import org.xhtmlrenderer.pdf.ITextFontResolver;  
import org.xhtmlrenderer.pdf.ITextRenderer;  import com.lowagie.text.pdf.BaseFont;  public class TestFlyingSauser {  public static void main(String[] args) throws Exception {  demo_1();  demo_2();  }  // 不支持中文  public static void demo_1() throws Exception {  String inputFile = "D:/Test/flying.html";  String url = new File(inputFile).toURI().toURL().toString();  String outputFile = "D:/Test/flying.pdf";  OutputStream os = new FileOutputStream(outputFile);  ITextRenderer renderer = new ITextRenderer();  renderer.setDocument(url);  renderer.layout();  renderer.createPDF(os);  os.close();  }  // 支持中文  public static void demo_2() throws Exception {  String outputFile = "D:/Test/demo_3.pdf";  OutputStream os = new FileOutputStream(outputFile);  ITextRenderer renderer = new ITextRenderer();  ITextFontResolver fontResolver = renderer.getFontResolver();  fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  StringBuffer html = new StringBuffer();  // DOCTYPE 必需写否则类似于 这样的字符解析会出现错误  html.append("<!DOCTYPE html PUBLIC /"-//W3C//DTD XHTML 1.0 Transitional//EN/" /"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd/">");  html.append("<html xmlns=/"http://www.w3.org/1999/xhtml/">").append("<head>")  .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")  .append("<mce:style type=/"text/css/"><!--  
body {font-family: SimSun;}  
--></mce:style><style type=/"text/css/" mce_bogus="1">body {font-family: SimSun;}</style>")  .append("</head>")  .append("<body>");  html.append("<div>支持中文!</div>");  html.append("</body></html>");  renderer.setDocumentFromString(html.toString());  // 解决图片的相对路径问题  // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");  renderer.layout();  renderer.createPDF(os);  os.close();  }  
}  

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

import java.awt.Insets;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.StringReader;  import org.zefer.pd4ml.PD4Constants;  
import org.zefer.pd4ml.PD4ML;  public class Converter {  public static void main(String[] args) throws Exception {  Converter converter = new Converter();  converter.generatePDF_2(new File("D:/Test/demo_ch_pd4ml_a.pdf"), "D:/Test/a.htm");  File pdfFile = new File("D:/Test/demo_ch_pd4ml.pdf");  StringBuffer html = new StringBuffer();  html.append("<html>")  .append("<head>")  .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")  .append("</head>")  .append("<body>")  .append("<font face=/"KaiTi_GB2312/">")  .append("<font color='red' size=22>显示中文</font>")  .append("</font>")  .append("</body></html>");  StringReader strReader = new StringReader(html.toString());  converter.generatePDF_1(pdfFile, strReader);  }  // 手动构造HTML代码  public void generatePDF_1(File outputPDFFile, StringReader strReader) throws Exception {  FileOutputStream fos = new FileOutputStream(outputPDFFile);  PD4ML pd4ml = new PD4ML();  pd4ml.setPageInsets(new Insets(20, 10, 10, 10));  pd4ml.setHtmlWidth(950);  pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));  pd4ml.useTTF("java:fonts", true);  pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312");  pd4ml.enableDebugInfo();  pd4ml.render(strReader, fos);  }  // HTML代码来自于HTML文件  public void generatePDF_2(File outputPDFFile, String inputHTMLFileName) throws Exception {  FileOutputStream fos = new FileOutputStream(outputPDFFile);  PD4ML pd4ml = new PD4ML();  pd4ml.setPageInsets(new Insets(20, 10, 10, 10));  pd4ml.setHtmlWidth(950);  pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));  pd4ml.useTTF("java:fonts", true);  pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312");  pd4ml.enableDebugInfo();  pd4ml.render("file:" + inputHTMLFileName, fos);  }  
}  

 参考资料:

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


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/328904.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java实现九九乘法表的输出

package cn.jbit.nestedloops; /*** 打印九九乘法表*/ public class MulTable {public static void main(String[] args) {int rows 9; //乘法表的行数for(int i 1; i<rows; i){ //一共9行for(int j 1; j < i; j){ //第i行有i个式子System.out.print(j"*&q…

成人教育计算机统考分数查询江苏省,江苏省教育考试院查询

阅读本文前&#xff0c;请您先点击上面的蓝色字体&#xff0c;再点击“关注”&#xff0c;这样您就可以继续免费收到最新文章了。每天都有分享。完全是免费订阅&#xff0c;请放心关注。注&#xff1a;本文转载自网络&#xff0c;不代表本平台立场&#xff0c;仅供读者参考&…

分布式系统事务一致性解决方案大对比,谁最好使?

“ 在分布式系统中&#xff0c;同时满足“一致性”、“可用性”和“分区容错性”三者是不可能的。分布式系统的事务一致性是一个技术难题&#xff0c;各种解决方案孰优孰劣&#xff1f; 老司机介绍 丁浪&#xff0c;现就职于某垂直电商平台&#xff0c;担任技术架构师。关注高并…

使用Java将HTML转成Word格式文件

转载自 使用Java将HTML转成Word格式文件 import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.Docum…

java百钱白鸡的算法

package cn.jbit.nestedloops;public class Chook {/*** 百钱买百鸡*/public static void main(String[] args) {int way 1; //买法int k 0; //雏鸡数for(int i1;i<20;i){ //公鸡数for(int j1;j<33;j){ //母鸡数k 100-i-j; //一共100只鸡if(k%3 0 && (5*i3…

.NET Core 工具遥测(应用信息收集)

说明&#xff1a;本文是个人翻译文章&#xff0c;由于个人水平有限&#xff0c;有不对的地方请大家帮忙更正。原文&#xff1a;.NET Core Tools Telemetry翻译&#xff1a;.NET Core 工具遥测&#xff08;应用信息收集&#xff09; .NET Core 工具遥测&#xff08;应用信息收集…

Jsoup学习总结

转载自 Jsoup学习总结摘要 Jsoup是一款比较好的Java版HTML解析器。可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API&#xff0c;可通过DOM&#xff0c;CSS以及类似于jQuery的操作方法来取出和操作数据。 jSOUP主要功能 从一个URL&#xff0c;文件或字符串中…

计算机发展阶段的划分是以什么作为标志,计算机以什么划分发展阶段

大家好&#xff0c;我是时间财富网智能客服时间君&#xff0c;上述问题将由我为大家进行解答。计算机是以电子元件来划分发展阶段的&#xff0c;即四个发展阶段&#xff0c;这就是人们通常所说的电子管、晶体管、集成电路、超大规模集成电路等四代。集成电路(integrated circui…

docker4dotnet #3 .net猿和小鲸鱼的苹果山之旅

.net猿遇到了小鲸鱼&#xff0c;觉得越来越兴奋。本来.net猿只是在透过家里那田子窗看外面的世界&#xff0c;但是看着海峡对岸的苹果园越来越茂盛&#xff0c;实在不想再去做一只宅猿了。于是&#xff0c;.net猿决定搭上小鲸鱼的渡轮到苹果园去看看。 .net猿上了小鲸鱼渡轮就先…

jsoup解析HTML用法小结

转载自 jsoup解析HTML用法小结使用HttpClientjsoup做采集器有一段时间了&#xff0c;发现jsoup很好用&#xff0c;而且还有很多方便的东西都没怎么用上。于是想根据官网上的cookbook来对jsoup的使用做个小结&#xff0c;或者是归纳。按功能分类做个列表&#xff0c;方便在写程…

java实现打印菱形

package cn.jbit.nestedloops; import java.util.Scanner; /*** 输入行数打印菱形*/ public class Diamond {public static void main(String[] args) {int rows 0; //菱形的行数Scanner input new Scanner(System.in);System.out.print("请输入菱形行数&#xff1a;&qu…

计算机二级vf上机试题,2016年计算机二级《VF》上机题及答案

2016年计算机二级《VF》上机题及答案二、综合应用题11设计一个表单名和文件名均为“bd2”的表单&#xff0c;所有控件的属性必须在表单设计器的属性窗口中设置。表单的标题为“外币市值情况”。表单中有一个文本框、一个表格和两个命令按钮“查询”和“关闭”。运行表单时&…

微软HTTP API指南

微软发布了创建“RESTful” API的指南。Roy Fielding将这些与REST没有多大关系的API称为HTTP API。 许多组织都发布了创建面向Web的HTTP API的建议&#xff0c;甚至是白宫都发布了一份标准——“白宫Web API标准”。近日&#xff0c;微软公开了他们的“微软REST API指南2.3”&a…

谈谈Memcached与Redis

转载自 谈谈Memcached与Redis1. Memcached简介 Memcached是以LiveJurnal旗下Danga Interactive公司的Bard Fitzpatric为首开发的高性能分布式内存缓存服务器。其本质上就是一个内存key-value数据库&#xff0c;但是不支持数据的持久化&#xff0c;服务器关闭之后数据全部丢失…

使用Akka.net开发第一个分布式应用

既然这个系列的主题是”基于消息的架构模型演变“&#xff0c;少不了说说Actor模型。Akka.net是一个基于Actor模型的分布式框架。如果你对分布式应用还非常陌生&#xff0c;当别人在谈”分布式“、”云计算“等名词时你感到茫然&#xff0c;那么本篇文章将带你进行一次分布式开…

用计算机控制英文,计算机控制

摘要&#xff1a;Flexible Manufacturing Systems-An Integrated Approach to Automate Production Operations;Growth of LD steelmaking in India;H{sub}2 optimal computer control: polynomial toolbox;Implementation of a real-time target tracking behavior using vide…

JAXP操作xml

转载自 JAXP操作xmlDOM对象详解1&#xff0e;基本的DOM对象 DOM的基本对象有5个&#xff1a;Document&#xff0c;Node&#xff0c;NodeList&#xff0c;Element和Attr。下面就这些对象的功能和实现的方法作一个大致的介绍。 Document 对象代表了整个XML的文档&#xff0c;所…

Aaron Stannard谈Akka.NET 1.1

Akka.NET 1.1近日发布&#xff0c;带来新特性和性能提升。InfoQ采访了Akka.net维护者Aaron Stannard&#xff0c;了解更多有关Akka.Streams和Akka.Cluster的信息。Aaron还阐述了与Akka for JVM实现有关的路线图计划。 InfoQ&#xff1a;这个版本有什么突出的特性&#xff1f; A…

以计算机网络为中介的人际传播,以计算机为中介的人际传播理论范式

20世纪90年代以来&#xff0c;以计算机为中介的传播(Computer-Mediated Communication&#xff0c;CMC)成为人类越来越普遍的经验。新技术深刻而全面地影响着人际传播的模式&#xff0c;并成为人际关系建立、发展和维系过程中不可或缺的因素。对实践过程的观察和研究形成了人际…

简单使用JDOM解析XML

转载自 简单使用JDOM解析XML使用JDOM解析XML一、前言 JDOM是Breet Mclaughlin和Jason Hunter两大Java高手的创作成果&#xff0c;2000年初&#xff0c;JDOM作为一个开放源代码项目正式开始研发。JDOM是一种解析XML的Java工具包。 DOM适合于当今流行的各种语言&#xf…