HTML转PDF

zoutuo 2010-04-09 03:15:15
各位大哥大街们,我想把HTML转换成PDF,使用的是FOP,但是报错:
java.lang.ClassCastException: org.apache.fop.layout.BlockArea cannot be cast to org.apache.fop.layout.AreaContainer
at com.test.Html2Pdf.fo2PDF(Html2Pdf.java:115)
115是driver.run()。程序代码如下:

package com.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;

import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.tools.DocumentInputSource;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;

/*
* Class that converts HTML to PDF using
* the DOM interfaces of JTidy, Xalan, and FOP.
*
* @author N. Afshartous
*
*/
public class Html2Pdf {

public static void main(String[] args) {

// open file
// if (args.length != 2) {
// System.out.println("Usage: Html2Pdf htmlFile styleSheet");
// System.exit(1);
// }

FileInputStream input = null;
String htmlFileName = "/home/zoutuo/hot_problem.html";
String styleSheet = "/home/zoutuo/xhtml2fo.xsl";
try {

input = new FileInputStream(htmlFileName);

} catch (java.io.FileNotFoundException e) {
System.out.println("File not found: " + htmlFileName);
}

Tidy tidy = new Tidy();
Document xmlDoc = tidy.parseDOM(input, null);

Document foDoc = xml2FO(xmlDoc, styleSheet);

String pdfFileName = htmlFileName.substring(0, htmlFileName.indexOf(".")) + ".pdf";
try {
OutputStream pdf = new FileOutputStream(new File(pdfFileName));
pdf.write(fo2PDF(foDoc));
} catch (java.io.FileNotFoundException e) {
System.out.println("Error creating PDF: " + pdfFileName);
} catch (java.io.IOException e) {
System.out.println("Error writing PDF: " + pdfFileName);
}

}

/*
* Applies stylesheet to input.
*
* @param xml The xml input Document
*
* @param stylesheet Name of the stylesheet
*
* @return Document Result of the transform
*/
private static Document xml2FO(Document xml, String styleSheet) {

DOMSource xmlDomSource = new DOMSource(xml);
DOMResult domResult = new DOMResult();

Transformer transformer = getTransformer(styleSheet);

if (transformer == null) {
System.out.println("Error creating transformer for " + styleSheet);
System.exit(1);
}
try {
transformer.transform(xmlDomSource, domResult);
} catch (javax.xml.transform.TransformerException e) {
return null;
}
return (Document) domResult.getNode();

}

/*
* Apply FOP to XSL-FO input
*
* @param foDocument The XSL-FO input
*
* @return byte[] PDF result
*/
private static byte[] fo2PDF(Document foDocument) {

DocumentInputSource fopInputSource = new DocumentInputSource(foDocument);
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);

Driver driver = new Driver(fopInputSource, out);
driver.setLogger(log);
driver.setRenderer(Driver.RENDER_PDF);
driver.run();

return out.toByteArray();

} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

/*
* Create and return a Transformer for the specified stylesheet.
*
* Based on the DOM2DOM.java example in the Xalan distribution.
*/
private static Transformer getTransformer(String styleSheet) {

try {

TransformerFactory tFactory = TransformerFactory.newInstance();

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();

dFactory.setNamespaceAware(true);

DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document xslDoc = dBuilder.parse(styleSheet);
DOMSource xslDomSource = new DOMSource(xslDoc);

return tFactory.newTransformer(xslDomSource);

} catch (javax.xml.transform.TransformerException e) {
e.printStackTrace();
return null;
} catch (java.io.IOException e) {
e.printStackTrace();
return null;
} catch (javax.xml.parsers.ParserConfigurationException e) {
e.printStackTrace();
return null;
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
return null;
}

}

}



各位清帮帮我吧,非常感谢!
...全文
631 21 打赏 收藏 转发到动态 举报
写回复
用AI写文章
21 条回复
切换为时间正序
请发表友善的回复…
发表回复
MRLIYUANWEN 2012-09-25
  • 打赏
  • 举报
回复
这是方法
public void ConvertHtmlToPdf(String paths,String[] pdfname,String[] htmlfile) throws Exception {
for (int i = 0; i < htmlfile.length; i++) {
File pdfFile = new File(paths + pdfname[i]);
pdfFile.getParentFile().mkdirs();
PdfCreatorApi pdfCreator = new PdfCreatorApi();
pdfCreator.setVisible(false);
pdfCreator.start("/NoProcessingAtStartup", true);
Map<String, Object> props = new HashMap<String, Object>();
props.put("UseAutosave", 1);
props.put("UseAutosaveDirectory", 1);
props.put("AutosaveFormat", 0);
props.put("AutosaveDirectory", pdfFile.getParentFile().getAbsolutePath());
props.put("AutosaveFilename", pdfFile.getName());
pdfCreator.setCoptions(props);
pdfCreator.clearCache();
String defPrint = pdfCreator.getDefaultPrinter();
pdfCreator.setDefaultPrinter("PDFCreator");
pdfCreator.setPrinterStop(false);
pdfCreator.invoke("cPrintURL", new Variant[] { new Variant(htmlfile[i]),new Variant(100) }); // 毫秒
int a = 1;
while (pdfCreator.getStatus() == PdfCreatorApi.STATUS_IN_PROGRESS) {
Thread.sleep(1000);
System.out.println("时间" + a);
if(a >= 10){
break;
}
++a;
}
pdfCreator.setDefaultPrinter(defPrint);
pdfCreator.clearCache();
pdfCreator.setPrinterStop(false);
pdfCreator.close();
PdfReader reader = new PdfReader(pdfFile.getAbsolutePath());
//assertEquals(2, reader.getNumberOfPages());
}

}

--这是测试类

try{
PDFCreatorHTML html = new PDFCreatorHTML();
//这是你文件放置的路径
String path ="F:\\jboss-4.0.1\\server\\default\\deploy\\tchwebstruts2.war\\tchdoc\\allpic\\";
String[] htmlfile= {"http://192.168.16.233:9080","http://www.sina.com.cn"};

//生成pdf的名称
String[] pdfname ={"人口系统.pdf","sina.pdf"};
html.ConvertHtmlToPdf(path,pdfname,htmlfile);

}catch(Exception e){
e.printStackTrace();
out.print(e.getMessage());
}
----还有一点就是 下载一个pdfcreator 安装下就可以运行了
javaXiaoJiang 2012-03-20
  • 打赏
  • 举报
回复
你好,请问,那个/home/zoutuo/hot_problem.html";
String styleSheet = "/home/zoutuo/xhtml2fo.xsl";是放在那个文件夹下的呢?
北极熊的冬天 2012-03-20
  • 打赏
  • 举报
回复
先将html转xml,再xml转fo,fo转pdf,目前有个问题是body标签下的中文内容能支持,但title标签下的中文内容就变为了#号了,有谁知道怎么解决么?
Modesty_5 2011-06-06
  • 打赏
  • 举报
回复
html2pdf
zoutuo 2010-05-10
  • 打赏
  • 举报
回复
有人能用YaHP转换中文网站吗?我只能转英文的,效果不错。但是中文的就会有问题。。。
jaisokforron 2010-05-10
  • 打赏
  • 举报
回复
继续顶
YangMacgrady 2010-05-07
  • 打赏
  • 举报
回复
只能帮顶了,呵呵。。。
hepeng_8 2010-05-07
  • 打赏
  • 举报
回复
这个功能是集成到服务器端的,用户要做的只是点一下按钮,这样做还要让用户下载一个不常用的浏览器,况且某些用户还不会安装软件……
zoutuo 2010-05-07
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 silence_smile 的回复:]

Google Chrome浏览器有个插件,可以直接把HTML页面转换成PDF
[/Quote]
这个功能是集成到服务器端的,用户要做的只是点一下按钮,这样做还要让用户下载一个不常用的浏览器,况且某些用户还不会安装软件……
zzg_boy 2010-04-12
  • 打赏
  • 举报
回复
顶!顶!顶!
Silence_Smile 2010-04-12
  • 打赏
  • 举报
回复
Google Chrome浏览器有个插件,可以直接把HTML页面转换成PDF
风再起时_2014 2010-04-12
  • 打赏
  • 举报
回复
帮顶了
麦穗 2010-04-12
  • 打赏
  • 举报
回复
我也只能帮你顶贴!
zoutuo 2010-04-10
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 bigbird2012 的回复:]

不行就写个适配器模式把两个接口转一下了
[/Quote]
什么意思?
zoutuo 2010-04-10
  • 打赏
  • 举报
回复
......................
BigBird2012 2010-04-09
  • 打赏
  • 举报
回复
不行就写个适配器模式把两个接口转一下了
injuer 2010-04-09
  • 打赏
  • 举报
回复
apache的子项目好用么..........

楼主有的全是高科技啊,我还在用的JACOB转呢............
zoutuo 2010-04-09
  • 打赏
  • 举报
回复
谢谢大家帮顶,有谁用过FOP分享一下经验,或者不用FOP也可以,只要能把HTML转换成PDF就可以
zzg_boy 2010-04-09
  • 打赏
  • 举报
回复
顶贴!友情帮顶1
wjz748305545 2010-04-09
  • 打赏
  • 举报
回复
我唯一能做的就是帮楼主顶这个帖子了
加载更多回复(1)

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧