You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Tanveer Alaie <ta...@gmail.com> on 2024/03/19 07:07:51 UTC

Query regarding printing and closing Jasper reports in Struts2.5

I am facing an issue with printing and closing Jasper reports in my Struts2
application. Here's a brief overview of the problem:

Description: In my Struts2 web application, I have a requirement to
generate Jasper reports and provide an option to print them directly from
the browser. Additionally, I need to automatically close the browser
tab/window after the report is printed.

Approach: I have tried implementing this functionality using JavaScript to
call an action class where I get jasper report print .

*Here's the JavaScript code on button click which call the action *

 var
url="/Ipd/dischargeManagement/bill_print?billNo="+val2+"&admissionId="+val1;
        var popupWin= window.open(url,'Report','menubar, toolbar,
location=center, directories, status, scrollbars, resizable, dependent,
width=600, height=400 left=210, top=260');

*struts2 action configuration *

 <action name="bill_print" class="com.skims.action.DischargeBillAction"
method="getBillPrint">
            <interceptor-ref name="prepare">
                <param name="excludeMethods">getBillPrint</param>
            </interceptor-ref>
            <result name="success" type="stream">
                <param name="contentType">application/pdf</param>
                <param name="inputName">inputStream</param>
                <param
name="contentDisposition">inline;filename="discharge_bill.pdf"</param>
                 <param name="contentLength">${contentLength}</param>
            </result>
            <result
name="input">/views/DischargeManagement/DischargeBill.jsp</result>

        </action>
*Action in controller*

public String getBillPrint() throws Exception {

            HttpServletResponse response =
ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            //Connection con = null;
            Map map = new HashMap();
            Connection con=null;

            Session session = null;
            Long admissionId=0l;
            Long billNo=0l;
            String empCode=null;
            String imgPath;
            //String wardName=null;
           System.out.println("formate id==="+dischargeBill.getId());

            try {
                    if(request.getParameter("admissionId")!=null)

 admissionId=Long.parseLong(request.getParameter("admissionId"));
                    if(request.getParameter("billNo")!=null)
                     billNo=Long.parseLong(request.getParameter("billNo"));
                    if(request.getParameter("empCode")!=null)
                     empCode=request.getParameter("empCode");
                session = HibernateUtil.getSessionFactory().openSession();
                SessionImpl sessionImpl = (SessionImpl) session;
                con = sessionImpl.connection();


                String reportPath;

                reportPath =
ServletActionContext.getServletContext().getRealPath("/Reports/DischargeBill.jasper");
                imgPath =
ServletActionContext.getServletContext().getRealPath("/images/logo.jpg");


                map.put("imgPath", imgPath);

                map.put("empCode",empCode);
                map.put("admissionId",admissionId);
                map.put("billNo",billNo);

                //System.out.println("sub report
path==="+ServletActionContext.getServletContext().getRealPath("/Reports").concat("\\"));


map.put("SUBREPORT_DIR",ServletActionContext.getServletContext().getRealPath("/Reports").concat("\\"));
                //
map.put("imgPath",ClassLoader.getSystemResourceAsStream("1LOGO.JPG"));
                //map.put(JRParameter.REPORT_FILE_RESOLVER, new
SimpleFileResolver(reportFile));
                JasperReport jasperReport = (JasperReport)
JRLoader.loadObjectFromFile(reportPath);
                net.sf.jasperreports.engine.JasperPrint jasperPrint =
JasperFillManager.fillReport(jasperReport, map, con);
              //for pdf format



                // Export PDF bytes
            ByteArrayOutputStream byteArrayOutputStream = new
ByteArrayOutputStream();
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT,
jasperPrint);
            exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,
byteArrayOutputStream);
            // Add JavaScript code to automatically print the PDF
            String javascript = "this.print({bUI: false, bSilent: true,
bShrinkToFit: true});this.close();";
            exporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT,
javascript);

            exporter.exportReport();

            // Set response headers
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline;
filename=discharge_bill.pdf");

            // Write PDF bytes to response output stream

 response.getOutputStream().write(byteArrayOutputStream.toByteArray());
             response.getOutputStream().flush();




            } catch (Exception e) {
                e.printStackTrace(System.out);
            } finally {
                if (con != null) {
                    con.close();
                }
                if (session != null) {
                    session.close();
                }
            }

            return SUCCESS;
        }

I would appreciate any insights, suggestions, or alternative approaches to
achieve reliable printing and closing of Jasper reports in a Struts2.5
application




Warm Regards,

Tanveer Ahmad Alaie,
Computer Associate,
Department of Electronics Communication & Information Technology,
* SKIMS,*
*Soura, Srinagar 190011, J&K (India). Cell: +91-9596044274*

Re: Query regarding printing and closing Jasper reports in Struts2.5

Posted by Tanveer Alaie <ta...@gmail.com>.
Thank you for your response

On Wed, 20 Mar, 2024, 1:04 pm Nate Kerkhofs, <Na...@ikan.be> wrote:

> Hi Tanveer,
>
> This isn't really a struts issue, but I'll answer regardless.
>
> There are security and usability issues related to automatic printing, so
> browsers block JavaScript from printing documents without user interaction.
> You won't be able to print pages automatically, you NEED to have the user
> confirm they want to print it through the browser print dialog. Those
> parameters you pass to the print() function have no effect in modern
> browsers. I'd recommend you open the PDF in the browser's PDF handler so
> the user can choose to click the print button in the browser's PDF handler
> itself.
>
> That said, it is possible to use the "afterprint" event in the browser to
> automatically execute JavaScript code to close the browser window after
> printing.
> https://developer.mozilla.org/en-US/docs/Web/API/Window/afterprint_event
>
> Regards,
>
> Nate Kerkhofs
>
> -----Original Message-----
> From: Tanveer Alaie <ta...@gmail.com>
> Sent: Tuesday, 19 March 2024 08:08
> To: user@struts.apache.org
> Subject: Query regarding printing and closing Jasper reports in Struts2.5
>
> I am facing an issue with printing and closing Jasper reports in my
> Struts2 application. Here's a brief overview of the problem:
>
> Description: In my Struts2 web application, I have a requirement to
> generate Jasper reports and provide an option to print them directly from
> the browser. Additionally, I need to automatically close the browser
> tab/window after the report is printed.
>
> Approach: I have tried implementing this functionality using JavaScript to
> call an action class where I get jasper report print .
>
> *Here's the JavaScript code on button click which call the action *
>
>  var
>
> url="/Ipd/dischargeManagement/bill_print?billNo="+val2+"&admissionId="+val1;
>         var popupWin= window.open(url,'Report','menubar, toolbar,
> location=center, directories, status, scrollbars, resizable, dependent,
> width=600, height=400 left=210, top=260');
>
> *struts2 action configuration *
>
>  <action name="bill_print" class="com.skims.action.DischargeBillAction"
> method="getBillPrint">
>             <interceptor-ref name="prepare">
>                 <param name="excludeMethods">getBillPrint</param>
>             </interceptor-ref>
>             <result name="success" type="stream">
>                 <param name="contentType">application/pdf</param>
>                 <param name="inputName">inputStream</param>
>                 <param
> name="contentDisposition">inline;filename="discharge_bill.pdf"</param>
>                  <param name="contentLength">${contentLength}</param>
>             </result>
>             <result
> name="input">/views/DischargeManagement/DischargeBill.jsp</result>
>
>         </action>
> *Action in controller*
>
> public String getBillPrint() throws Exception {
>
>             HttpServletResponse response =
> ServletActionContext.getResponse();
>             HttpServletRequest request = ServletActionContext.getRequest();
>             //Connection con = null;
>             Map map = new HashMap();
>             Connection con=null;
>
>             Session session = null;
>             Long admissionId=0l;
>             Long billNo=0l;
>             String empCode=null;
>             String imgPath;
>             //String wardName=null;
>            System.out.println("formate id==="+dischargeBill.getId());
>
>             try {
>                     if(request.getParameter("admissionId")!=null)
>
>  admissionId=Long.parseLong(request.getParameter("admissionId"));
>                     if(request.getParameter("billNo")!=null)
>                      billNo=Long.parseLong(request.getParameter("billNo"));
>                     if(request.getParameter("empCode")!=null)
>                      empCode=request.getParameter("empCode");
>                 session = HibernateUtil.getSessionFactory().openSession();
>                 SessionImpl sessionImpl = (SessionImpl) session;
>                 con = sessionImpl.connection();
>
>
>                 String reportPath;
>
>                 reportPath =
>
> ServletActionContext.getServletContext().getRealPath("/Reports/DischargeBill.jasper");
>                 imgPath =
> ServletActionContext.getServletContext().getRealPath("/images/logo.jpg");
>
>
>                 map.put("imgPath", imgPath);
>
>                 map.put("empCode",empCode);
>                 map.put("admissionId",admissionId);
>                 map.put("billNo",billNo);
>
>                 //System.out.println("sub report
> path==="+ServletActionContext.getServletContext().getRealPath("/Reports").concat("\\"));
>
>
>
> map.put("SUBREPORT_DIR",ServletActionContext.getServletContext().getRealPath("/Reports").concat("\\"));
>                 //
> map.put("imgPath",ClassLoader.getSystemResourceAsStream("1LOGO.JPG"));
>                 //map.put(JRParameter.REPORT_FILE_RESOLVER, new
> SimpleFileResolver(reportFile));
>                 JasperReport jasperReport = (JasperReport)
> JRLoader.loadObjectFromFile(reportPath);
>                 net.sf.jasperreports.engine.JasperPrint jasperPrint =
> JasperFillManager.fillReport(jasperReport, map, con);
>               //for pdf format
>
>
>
>                 // Export PDF bytes
>             ByteArrayOutputStream byteArrayOutputStream = new
> ByteArrayOutputStream();
>             JRPdfExporter exporter = new JRPdfExporter();
>             exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT,
> jasperPrint);
>             exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,
> byteArrayOutputStream);
>             // Add JavaScript code to automatically print the PDF
>             String javascript = "this.print({bUI: false, bSilent: true,
> bShrinkToFit: true});this.close();";
>             exporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT,
> javascript);
>
>             exporter.exportReport();
>
>             // Set response headers
>             response.setContentType("application/pdf");
>             response.setHeader("Content-Disposition", "inline;
> filename=discharge_bill.pdf");
>
>             // Write PDF bytes to response output stream
>
>  response.getOutputStream().write(byteArrayOutputStream.toByteArray());
>              response.getOutputStream().flush();
>
>
>
>
>             } catch (Exception e) {
>                 e.printStackTrace(System.out);
>             } finally {
>                 if (con != null) {
>                     con.close();
>                 }
>                 if (session != null) {
>                     session.close();
>                 }
>             }
>
>             return SUCCESS;
>         }
>
> I would appreciate any insights, suggestions, or alternative approaches to
> achieve reliable printing and closing of Jasper reports in a Struts2.5
> application
>
>
>
>
> Warm Regards,
>
> Tanveer Ahmad Alaie,
> Computer Associate,
> Department of Electronics Communication & Information Technology,
> * SKIMS,*
> *Soura, Srinagar 190011, J&K (India). Cell: +91-9596044274*
>

RE: Query regarding printing and closing Jasper reports in Struts2.5

Posted by Nate Kerkhofs <Na...@ikan.be>.
Hi Tanveer,

This isn't really a struts issue, but I'll answer regardless.

There are security and usability issues related to automatic printing, so browsers block JavaScript from printing documents without user interaction. You won't be able to print pages automatically, you NEED to have the user confirm they want to print it through the browser print dialog. Those parameters you pass to the print() function have no effect in modern browsers. I'd recommend you open the PDF in the browser's PDF handler so the user can choose to click the print button in the browser's PDF handler itself.

That said, it is possible to use the "afterprint" event in the browser to automatically execute JavaScript code to close the browser window after printing. https://developer.mozilla.org/en-US/docs/Web/API/Window/afterprint_event

Regards,

Nate Kerkhofs

-----Original Message-----
From: Tanveer Alaie <ta...@gmail.com> 
Sent: Tuesday, 19 March 2024 08:08
To: user@struts.apache.org
Subject: Query regarding printing and closing Jasper reports in Struts2.5

I am facing an issue with printing and closing Jasper reports in my Struts2 application. Here's a brief overview of the problem:

Description: In my Struts2 web application, I have a requirement to generate Jasper reports and provide an option to print them directly from the browser. Additionally, I need to automatically close the browser tab/window after the report is printed.

Approach: I have tried implementing this functionality using JavaScript to call an action class where I get jasper report print .

*Here's the JavaScript code on button click which call the action *

 var
url="/Ipd/dischargeManagement/bill_print?billNo="+val2+"&admissionId="+val1;
        var popupWin= window.open(url,'Report','menubar, toolbar, location=center, directories, status, scrollbars, resizable, dependent, width=600, height=400 left=210, top=260');

*struts2 action configuration *

 <action name="bill_print" class="com.skims.action.DischargeBillAction"
method="getBillPrint">
            <interceptor-ref name="prepare">
                <param name="excludeMethods">getBillPrint</param>
            </interceptor-ref>
            <result name="success" type="stream">
                <param name="contentType">application/pdf</param>
                <param name="inputName">inputStream</param>
                <param
name="contentDisposition">inline;filename="discharge_bill.pdf"</param>
                 <param name="contentLength">${contentLength}</param>
            </result>
            <result
name="input">/views/DischargeManagement/DischargeBill.jsp</result>

        </action>
*Action in controller*

public String getBillPrint() throws Exception {

            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            //Connection con = null;
            Map map = new HashMap();
            Connection con=null;

            Session session = null;
            Long admissionId=0l;
            Long billNo=0l;
            String empCode=null;
            String imgPath;
            //String wardName=null;
           System.out.println("formate id==="+dischargeBill.getId());

            try {
                    if(request.getParameter("admissionId")!=null)

 admissionId=Long.parseLong(request.getParameter("admissionId"));
                    if(request.getParameter("billNo")!=null)
                     billNo=Long.parseLong(request.getParameter("billNo"));
                    if(request.getParameter("empCode")!=null)
                     empCode=request.getParameter("empCode");
                session = HibernateUtil.getSessionFactory().openSession();
                SessionImpl sessionImpl = (SessionImpl) session;
                con = sessionImpl.connection();


                String reportPath;

                reportPath =
ServletActionContext.getServletContext().getRealPath("/Reports/DischargeBill.jasper");
                imgPath =
ServletActionContext.getServletContext().getRealPath("/images/logo.jpg");


                map.put("imgPath", imgPath);

                map.put("empCode",empCode);
                map.put("admissionId",admissionId);
                map.put("billNo",billNo);

                //System.out.println("sub report path==="+ServletActionContext.getServletContext().getRealPath("/Reports").concat("\\"));


map.put("SUBREPORT_DIR",ServletActionContext.getServletContext().getRealPath("/Reports").concat("\\"));
                //
map.put("imgPath",ClassLoader.getSystemResourceAsStream("1LOGO.JPG"));
                //map.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportFile));
                JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportPath);
                net.sf.jasperreports.engine.JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, con);
              //for pdf format



                // Export PDF bytes
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT,
jasperPrint);
            exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,
byteArrayOutputStream);
            // Add JavaScript code to automatically print the PDF
            String javascript = "this.print({bUI: false, bSilent: true,
bShrinkToFit: true});this.close();";
            exporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT,
javascript);

            exporter.exportReport();

            // Set response headers
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline; filename=discharge_bill.pdf");

            // Write PDF bytes to response output stream

 response.getOutputStream().write(byteArrayOutputStream.toByteArray());
             response.getOutputStream().flush();




            } catch (Exception e) {
                e.printStackTrace(System.out);
            } finally {
                if (con != null) {
                    con.close();
                }
                if (session != null) {
                    session.close();
                }
            }

            return SUCCESS;
        }

I would appreciate any insights, suggestions, or alternative approaches to achieve reliable printing and closing of Jasper reports in a Struts2.5 application




Warm Regards,

Tanveer Ahmad Alaie,
Computer Associate,
Department of Electronics Communication & Information Technology,
* SKIMS,*
*Soura, Srinagar 190011, J&K (India). Cell: +91-9596044274*