java 将 Freemarker 转换为 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5676686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting Freemarker To PDF
提问by MilindaD
I am designing reports using freemarker, I have a problem where I need the processed output in a PDF format.
我正在使用 freemarker 设计报告,我遇到了需要 PDF 格式的处理输出的问题。
What I want to do is to pass an HTML + CSS fremarker template to the freemarker engine and output the processed HTML as an PDF. The current problem I have is on how to convert the processed freemarker to a PDF
我想要做的是将 HTML + CSS fremarker 模板传递给 freemarker 引擎并将处理后的 HTML 输出为 PDF。我目前的问题是如何将处理过的 freemarker 转换为 PDF
try {
Configuration cfg = new Configuration();
Template tpl = cfg.getTemplate("example.ftl");
OutputStreamWriter output = new OutputStreamWriter(System.out);
Map testHashMap = new HashMap();
testHashMap.put("test", "testValue");
tpl.process(testHashMap, output);
} catch (Exception e) {
e.printStackTrace();
}
While searching on thje internet I couldnt find any information on this topic, but I found out about the iText framework
在 thje Internet 上搜索时,我找不到有关此主题的任何信息,但我发现了有关 iText 框架的信息
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new StringBufferInputStream(buf.toString()));
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
OutputStream os = response.getOutputStream();
renderer.createPDF(os);
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
The problem now is how do I combine these two code fragments to generate a pdf?
现在的问题是我如何组合这两个代码片段来生成一个pdf?
All help is really appreciated
非常感谢所有帮助
Regards, MilindaD
问候, MilindaD
采纳答案by Riccardo Cossu
I think it would be better to use two different pipelines and see them as two different views of the same model.
我认为最好使用两个不同的管道并将它们视为同一模型的两个不同视图。
Data -> Freemarker transfomer -> HTML
数据 -> Freemarker 转换器 -> HTML
Data -> iText transformer -> pdf
数据 -> iText 转换器 -> pdf
or you could use XSLT on the html and use XSL-FO like Apache FOP, but it seems overkill to me.
或者您可以在 html 上使用 XSLT 并像 Apache FOP 一样使用 XSL-FO,但这对我来说似乎有点过分。
回答by AConsumer
I would NOTsuggest to use iTextas it comes under AGPLlicense.
我不建议使用iText,因为它受AGPL许可。
If you provide a service based on software you got under AGPL licensing, you need to provide free access to the complete software for the service (probably with the limits implied by the “mere aggregation” concept).
如果您提供基于根据 AGPL 许可获得的软件的服务,您需要提供对该服务的完整软件的免费访问(可能具有“纯粹聚合”概念所隐含的限制)。
You can use openhtmtopdffor commercial purpose as well for free as it comes under LGPL license.
您可以将openhtmtopdf用于商业目的,也可以免费使用,因为它受 LGPL 许可。