Search code examples
jsfjasper-reports

Print PDF report directly instead of downloading, opening and printing it


I developed a JSF application which gives a pdf file as a download after each transaction at the client machine using JasperReports. I followed this tutorial. Is there any way we can directly print it rather than downloading it as the end user has to open it and give the print command. (Customers say that there are lot of transactions and they want to print the receipt in the same manner in a standalone application without any intervention like bringing the print dialog.)


Solution

  • You cannot force the browser to print without a print dialog appearing.

    You can, however, set the Content-Disposition such that the browser opens up a PDF in the browser that can be printed. For example:

      /**
       * Sets the regular HTTP headers, regardless of whether this report is
       * embedded in the browser window, or causes a "Save As" dialog prompt to
       * download.
       */
      protected void setHeaders() {
        getServletResponse().setHeader( "Cache-Control", getCacheControl() );
      }
    
      /**
       * Sets the HTTP headers required to indicate to the browser that the
       * report is to be downloaded (rather than displayed in the current
       * window).
       */
      protected void setDownloadHeaders() {
        HttpServletResponse response = getServletResponse();
        response.setHeader( "Content-Description", getContentDescription() );
        response.setHeader( "Content-Disposition", "attachment, filename="
          + getFilename() );
        response.setHeader( "Content-Type", getContentType() );
        response.setHeader( "Content-Transfer-Encoding",
          getContentTransferEncoding() );
      }
    

    This will prompt the user to save the PDF. If you change the Content-Disposition, the browser will display the PDF inline without prompting to save. This will skip the step of having to open the PDF.