The situation: I need to capture a screenshot of the screen with html2canvas, get the resulting dataURL, send it to a backing bean, generate a JasperReport with the picture, and open the download dialog so the user can download a PDF with a picture of the screen in it.
My attempted solution (which is not working 100%):
This is the command link that does everything:
<p:commandLink ajax="true" value="Print PDF" onclick="printPDF();" oncomplete="clickPrintButton();" />
The printPDF() function in my javascript file:
function printPDF() {
html2canvas($('#mainForm'), {
onrendered : function(canvas) {
var dataURL = canvas.toDataURL("image/png");
var hiddenField = document.getElementById('mainForm:dataURLfield');
hiddenField.setAttribute('value', dataURL);
hiddenField.onchange();
}
});
}
As you can see, I send the dataURL value to a hidden field and call the onchange() event. This is my hidden field:
<h:inputText id="dataURLfield" style="display:none">
<f:ajax event="change" listener="#{myController.printPDFListener}" />
</h:inputText>
In the listener for the change event I set a property in myController with the value of the dataURL. After the ajax completes, the image is supposed to be properly saved in my backing bean, and I should be able to generate the report and start the file download.
The function that is called on the 'oncomplete' event:
function clickPrintButton(){
var hiddenButton = document.getElementById('mainForm:printPDFButton');
hiddenButton.click();
}
The hidden button which is supposed to start the file download:
<h:commandButton ajax="false" id="printPDFButton" style="display:none">
<p:fileDownload value="#{myController.downloadPDF}" />
</h:commandButton>
The problem is, sometimes it works, sometimes it doesn't, sometimes I get an error in the page, sometimes I get a blank PDF. What do you guys think? Any ideas?