Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Freemarker To PDF

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

like image 288
MilindaD Avatar asked Apr 15 '11 12:04

MilindaD


2 Answers

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.

like image 82
Riccardo Cossu Avatar answered Sep 30 '22 10:09

Riccardo Cossu


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.

like image 23
AConsumer Avatar answered Sep 30 '22 11:09

AConsumer