使用飞碟将xhtml字符串转换为PDF的最简单方法是什么? [英] What's the easiest way of converting an xhtml string to PDF using Flying Saucer?

查看:137
本文介绍了使用飞碟将xhtml字符串转换为PDF的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用飞碟一段时间了,效果非常好

I've been using Flying Saucer for a while now with awesome results.

我可以像这样通过uri设置文档

I can set a document via uri like so

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(xhtmlUri);

这很好,因为它将解析所有相对于给定URI的相对CSS资源等.但是,我现在正在生成xhtml,并希望将其直接呈现为PDF(不保存文件).

Which is nice, as it will resolve all relative css resources etc relative to the given URI. However, I'm now generating the xhtml, and want to render it directly to a PDF (without saving a file). The appropriate methods in ITextRenderer seem to be:

private Document loadDocument(final String uri) {
    return _sharedContext.getUac().getXMLResource(uri).getDocument();
}

public void setDocument(String uri) {
    setDocument(loadDocument(uri), uri);
}

public void setDocument(Document doc, String url) {
    setDocument(doc, url, new XhtmlNamespaceHandler());
}

如您所见,我现有的代码仅提供了uri,而ITextRenderer为我创建了Document.

As you can see, my existing code just gives the uri and ITextRenderer does the work of creating the Document for me.

从格式化的xhtml字符串创建Document的最短方法是什么?我宁愿使用现有的Flying Saucer库,而不必导入另一个XML解析罐(只是为了保持一致的错误和功能).

What's the shortest way of creating the Document from my formatted xhtml String? I'd prefer to use the existing Flying Saucer libs without having to import another XML parsing jar (just for the sake of consistent bugs and functionality).

推荐答案

以下作品:

Document document = XMLResource.load(new ByteArrayInputStream(templateString.getBytes())).getDocument();

以前,我曾尝试过

final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);

final DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
Document document = documentBuilder.parse(new ByteArrayInputStream(templateString.getBytes()));

但是失败了,因为它尝试从 http://www.w3.org 下载HTML docType. (对于Java库,它返回503).

but that fails as it attempts to download the HTML docType from http://www.w3.org (which returns 503's for the java libs).

这篇关于使用飞碟将xhtml字符串转换为PDF的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆