Search code examples
javajsfjbossseam

JSF/Seam: How to download and print a dynamically generated PDF file without user intervention?


I have a JSF/Seam web app which has a page with a form which, when submitted (button clicked), causes a PDF file to be dynamically created (in Java, server side) based on the form input. Currently what I have working is that the resulting PDF is returned to the browser as a file download, so the user can opt to save it or open it in Acrobat Reader for subsequent printing.

What I would like to happen is that the PDF is sent to the browser and printed (client side) without further user intervention (well, other than perhaps the Windows printer options dialog appearing, about which there's nothing I could do).

The solution seems to be based on having a hidden iframe on the page into which the PDF is loaded and then calling .contentWindow.print() on the iframe. However, I have no idea how to get the PDF into the iframe via the HttpServletResponse (in Java), much less how to automatically call print() on the iframe once the pdf has been loaded.


Solution

  • However, I have no idea how to get the PDF into the iframe via the HttpServletResponse (in Java)

    Let the <iframe src> point to a servlet URL which gets an InputStream of the PDF and writes it to the OutputStream of the response. You can if necessary pass JSF bean properties as additional GET parameters so that you can control the PDF generation.

    <iframe src="pdfServlet?foo=#{bean.foo}&amp;bar=#{bean.bar}"></iframe>
    

    The doGet() method of the servlet in question can look like this:

    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    
    response.setContentType("application/pdf");
    
    InputStream input = generatePdfSomehowBasedOn(foo, bar);
    OutputStream output = response.getOutputStream();
    // Now just write input to output.
    

    much less how to automatically call print() on the iframe once the pdf has been loaded.

    Hook a function on <iframe onload>. You however need to take browser specific behaviours into account. More hints can be found in this question: How do I print an IFrame from javascript in Safari/Chrome