I have pdf file in my application. I need to display the pdf in browser. I am reading the file as a fileInputStream, I need to display the pdf in browser with in my applica
In your servlet, set the MIME type to the correct one for PDF : application/pdf
See http://www.iana.org/assignments/media-types/
You will have to write your InputStream
to your response OutputStream
as follows:
Content-Disposition
will have to be inline
.Content-Type
will have to be application/pdf
.Content-Length
will be the length (in bytes) of the total data in the InputStream
.Once set, write the input stream data to output stream of the response.
Something of this effect:
/* (non-Javadoc)
* @see org.bfs.bayweb.util.renderer.ServletViewRenderer#render(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
public void render(ServletRequest request, ServletResponse response) throws IOException {
// TODO Auto-generated method stub
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int inputStreamLength = 0;
int length = 0;
while ((length = getInputStream().read(buffer)) > 0) {
inputStreamLength += length;
baos.write(buffer, 0, length);
}
if (inputStreamLength > getContentLength()) {
setContentLength(inputStreamLength);
}
if (response instanceof HttpServletResponse) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.reset();
httpResponse.setHeader("Content-Type", getContentType());
httpResponse.setHeader("Content-Length", String.valueOf(getContentLength()));
httpResponse.setHeader("Content-Disposition", "\"" + getContentDisposition() + "\"" + ((getFileName() != null && !getFileName().isEmpty()) ? "; filename=\"" + getFileName() + "\"": ""));
}
response.getOutputStream().write(baos.toByteArray(), 0, (int)getContentLength());
//finally
response.getOutputStream().flush();
//clear
baos = null;
} finally {
// TODO Auto-generated catch block
close(response.getOutputStream());
close(getInputStream());
}
}
private void close(Closeable resource) throws IOException {
if (resource != null) {
resource.close();
}
}