开发者

Converting Freemarker To PDF

开发者 https://www.devze.com 2023-02-25 06:23 出处:网络
I am designing reports using freemarker, I have a problem where I need the processed output in a PDF format.

I am designing reports using freemarker, I have a problem where I need the processed output in a PDF format.

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

    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

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?

All help is really appr开发者_开发技巧eciated

Regards, MilindaD


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

Data -> iText transformer -> pdf

or you could use XSLT on the html and use XSL-FO like Apache FOP, but it seems overkill to me.


I would NOT suggest to use iText as it comes under AGPL license.

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).

You can use openhtmtopdf for commercial purpose as well for free as it comes under LGPL license.


Pupeteer seems to be a good option. You can run a separate node process to access your API and print.

https://blog.risingstack.com/pdf-from-html-node-js-puppeteer/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号