Search code examples
javajasper-reports

Send pdf jasper straight to the printer in web app


I need to send a pdf jasper directly to the printer, the current code PDF is delegated to the browser and therefore the user can print as many copies as desired. Must allow only print one copy, so I thought I'd send directly to printing. I searched the forum but did not understand what would be the best solution to the issue.

Take a look at my code:

public class UtilRelatorios {

public static void imprimeRelatorio(String relatorioNome,
        HashMap parametros) throws IOException, JRException {
        FacesContext fc = FacesContext.getCurrentInstance();
        ServletContext context = (ServletContext) fc.getExternalContext().getContext();
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        JasperPrint jasperPrint = 
                JasperFillManager.fillReport(
                        context.getRealPath("/relatorios")+ File.separator+relatorioNome+".jasper",
                        parametros);    
        //int finalPag = jasperPrint.getPages().size();
        //System.out.println("page: "+finalPag);
        //JasperPrintManager.printPage(jasperPrint,finalPag,false);
        byte[] b = null;
        //JasperPrintManager.printPage(jasperPrint, 0, false);

        try {
            b = JasperExportManager.exportReportToPdf(jasperPrint);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }    

            if (b != null && b.length > 0) {
                // Envia o relatório em formato PDF para o browser
                response.setContentType("application/pdf");
                int codigo = (int) (Math.random()*1000);
                response.setHeader("Content-disposition","inline);filename=relatorio_"+codigo+".pdf");
                response.setContentLength(b.length);
                ServletOutputStream ouputStream = response.getOutputStream();
                ouputStream.write(b, 0, b.length);
                ouputStream.flush();
                ouputStream.close();
            }   
 }

}


Solution

  • If as seems in question you like to send the report directly to user's printer via web application, browser.

    This can not be done!, you can not control the web users printer directly from the browser (excluding the use of activeX or other home made plugins)

    Probably this is luck since otherwise while navigating on internet you would have people printing alot of advertising on your printer....

    If instead you like to send it to a printer attached to server, this can be done!

    If its the server printer please let me know and I can pass you some code.