Converting Freemarker To PDF

19,578

Solution 1

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.

Solution 2

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.

Share:
19,578
MilindaD
Author by

MilindaD

Software Engineer :)

Updated on June 04, 2022

Comments

  • MilindaD
    MilindaD about 2 years

    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 appreciated

    Regards, MilindaD