Send pdf jasper straight to the printer in web app

2019-09-01 15:37发布

问题:

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();
            }   
 }

}

回答1:

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.



回答2:

If the client & server PC are on the same network ie LAN, you can share the client's printer on the server, then send report to it just like you'd send to a locally installed printer.