Issue
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();
}
}
}
Badly stuck. Any help would be appreciated. Thank you.
Solution
since it was from the same page intialize 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();
Answered By - Soniya Mohan
Answer Checked By - Terry (JavaFixing Volunteer)