PDF generation using iText in Struts-2 : result type stream not working

后端 未结 2 1978
無奈伤痛
無奈伤痛 2020-12-18 08:16

My requirement is to generate PDF file using iText, I use below code to create a sample PDF

Document document = new Document();
ByteArrayOutputStream baos =          


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 09:15

    Found solution to this.

    The method in the action which performs this PDF export can be void. The result type configuration is not needed while we are writing directly to response's outputstream

    for example, have your action class this way

    Class ExportReportAction extends ActionSupport {
      public void exportToPdf() { // no return type
        try {
            Document document = new Document();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            document.open();
            document.add(new Paragraph("success PDF FROM STRUTS"));
            document.close(); 
            ServletOutputStream outputStream = response.getOutputStream() ; 
            baos.writeTo(outputStream); 
            response.setHeader("Content-Disposition", "attachment; filename=\"stuReport.pdf\""); 
            response.setContentType("application/pdf"); 
            outputStream.flush(); 
            outputStream.close(); 
        }catch (Exception e) {
            //catch
        }
    
      } 
    }
    

    and have your struts-configuration this way

     
     
    
    

    this works cool !!!

    Thanks for all who attempted to answer this question

提交回复
热议问题