Skip to content
Advertisement

Struts pdf view showing null pointer exception in response object

I have created a pdf with iTextpdf but while setting the response.setContentType("application/pdf"); getting null pointer exception

From jsp

<form action="pdfReport">
                    <input formtarget="_blank" type="image"   src="${pageContext.request.contextPath}/images/pdf-icon.png" id="pdf"  ">
                    </form>

struts.xml

<action name="pdfReport" class="com.tapal.action.CreateReceiptAction" method="generatePdfReport">       
            <result name="success" type="stream">
                <param name="contentType">application/pdf</param>
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">inline;filename="eTapalReport.pdf"</param>
                <param name="bufferSize">1024</param>
            </result> 
        </action>

action class

public class CreateReceiptAction extends BaseAction implements ServletRequestAware{


// codes


public String generatePdfReport() {
      try {

//generated pdf 


String filePathToBeServed = pdfPath+"/"+pdfname;;
        File fileToDownload = new File(filePathToBeServed);
        InputStream inputStream = new FileInputStream(fileToDownload);
        response.setContentType("application/pdf"); // here nullPointer exception
        response.addHeader("content-disposition", "inline; filename=eTapalReport.pdf");

        IOUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();
        inputStream.close();  
        fOut.close();   
    }
      
    catch (Exception e) {
        e.printStackTrace();
    }
}
}

Advertisement

Answer

Since it was from the same page intializing the response, reset and closing worked for me

 response= ServletActionContext.getResponse();      
                String filePathToBeServed = pdfPath+"/"+pdfname;;
                File fileToDownload = new File(filePathToBeServed);
                InputStream inputStream = new FileInputStream(fileToDownload);
                response.setContentType("application/pdf");
                response.addHeader("content-disposition", "inline; filename=eTapalReport.pdf");
                response.reset();

                IOUtils.copy(inputStream, response.getOutputStream());
                response.flushBuffer();
                
                inputStream.close();  
                response.getOutputStream().close();

        
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement