简体   繁体   中英

Play Framework: Generate PDF from template that uses Javascript for graphing

I have a template that has some Javascript used to generate graphs in the browser. I would like to use that same template to create a PDF and send as an attachment in an e-mail. In this scenario, there would be no browser/client interaction.

I am using the PDF module that is available from the Play website and I have managed to get the PDF rendering to work. The only issue is that the graphs don't show up in the PDF but all other static text does. I'm assuming the graphs aren't appearing in the PDF due to the Javascript not being executed prior to the PDF generation.

Does anyone have any ideas on how to get around this problem?

Since you are using the Play framework, the easiest way is likely to be using Rhino. http://www.mozilla.org/rhino/ That is Mozilla's implementation of Javascript to run on the JVM, which is what the Play framework runs on. You may have to make some changes to the Javascript, for instance if it uses the browser Canvas API you would have to make a facade object that sends those drawing commands to the PDF drawing object instead of the screen. Or to both places if that is what you want.

You might get a more detailed answer if you give some more information about the Javascript graphing code.

I don´t know if this helps you, but this is what worked really fast for me.

I transformed the canvas into a PNG with:

var datastring = document.getElementById('myCanvas').toDataURL("image/png");

Then I sent that datastring to the server so that Play generates a PDF and I passed the variable to the PDF Generator

public static void reportPDF(String graphData){
    PDF.renderPDF(graphData);
}

My pdf code looks like this:

    <body>
        <img width="100%" src="${graphData}"/>
    </body>

If you won't find better options consider using itext directly. It's a pdf rendering library that is used in pdf-plugin. You'll have to manually rewrite template in terms of pdf generation but you'll have full control of the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM