Display Pdf file in browser using Servlet - java

I am using intellij Idea and I have saved my pdf file in resources folder. I want to display that pdf file in browser.
public class GetDocumentation extends HttpServlet {
private static final Logger log = Logger.getLogger(GetDocumentation.class);
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream pdf_path = this.getClass().getResourceAsStream(ApplicationProperties.getProperty("PDF_PATH"));
resp.setContentType("application/pdf");
resp.addHeader("Content-Disposition", "attachment; filename=Documentation.pdf");
OutputStream responseOutputStream = resp.getOutputStream();
byte[] buf = new byte[4096];
int len = -1;
while ((len = pdf_path.read(buf)) != -1) {
responseOutputStream.write(buf, 0, len);
}
responseOutputStream.flush();
responseOutputStream.close();
}
}
Documentation
I am using Jsp servlet and I am calling "/documentation". And my file is getting rendered but it's blank. Am I doing anything wrong?

inline Content-Disposition should be used to display the document. Replace "attachment" with "inline":
resp.addHeader("Content-Disposition", "inline; filename=Documentation.pdf");

Related

servlet is showing java.io.FileNotFoundException: ?E:\guru99\test.txt (The filename, directory name, or volume label syntax is incorrect)

My servlet is showing this exception but the file exist at that location.
java.io.FileNotFoundException: ?E:\guru99\test.txt (The filename, directory name, or volume label syntax is incorrect)
Servlet Code,
#WebServlet(urlPatterns = {"/image_download"})
public class image_download extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String gurufile = "test.txt";
String gurupath = "‪E:\\guru99\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + gurufile + "\"");
FileInputStream fileInputStream = new FileInputStream(gurupath + gurufile);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I want to download the file from the link I provided.
Your issue is duplicate of this SO question
As when I tried to copy your code to my eclipse , I got same prompt about Save Problems. Somewhere there is an invalid character & string with that char can't be parsed into valid file path.
I manually retyped values for String gurufile & String gurupath instead of copy pasting your code & it worked successfully. Culprit seems String gurupath.
Second point is usage of try-with-resource ( though that has nothing to do with your issue ) instead of explicitly trying to close out resources,
response.setContentType("text/html");
String gurufile = "test.txt";
String gurupath = "D:\\guru99\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + gurufile + "\"");
try (FileInputStream fileInputStream = new FileInputStream(gurupath + gurufile);
PrintWriter out = response.getWriter();) {
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
}
Copy - paste my code to see if this resolves your problem.

Java GWT cannot open downloaded xlsx file

I'm new to GWT and in my company i was asked to make some changes in one of our applications.
Currently the Program generates reports in .xls format. Now we want to change it to .xlsx
public class Download extends HttpServlet {
private static final long serialVersionUID = 5580666921970339383L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename = (String)request.getSession().getAttribute(CrossReportConstants.ATTR_FILENAME);
byte[] data = (byte[])request.getSession().getAttribute(CrossReportConstants.ATTR_REPORT);
request.getSession().setAttribute(CrossReportConstants.ATTR_FILENAME, null);
request.getSession().setAttribute(CrossReportConstants.ATTR_REPORT, null);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setContentLength(data.length);
try {
InputStream in = new ByteArrayInputStream(data);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
// copy binary contect to output stream
while (in.read(outputByte, 0, 4096) != -1) {
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I changed response.setContentType("application/vnd.ms-excel"); to
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
and I changed the filename to exampleReport.xlsx
When i test the Application i can download the report but i cannot open it - Excel tells me the file is corrupted. (the file has the right size and when i open it in a text editor i can see the content)
Did I miss something?
Thanks in advance

How to convert byte[] to PDF in java servlet?

I am trying to create a PDF file out of a byte array. Before writing the bytes to the file I print them as a string and the contents get printed correctly but when I open the automatically downloaded PDF file, it won't open as the file is somehow damaged.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long logFileId = Long.valueOf(request.getParameter(REQUEST_PARAM_DOCUMENT_ID));
MappingInfo mapping = documentService.getMapping(logFileId);
byte[] file = mapping.getImportLogs();
System.out.println(new String(file));
response.setContentType("application/pdf");
response.setContentLength(file.length);
// response.reset();
response.setContentType("application/pdf");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=ImportLog.pdf");
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
outStream.write(file);
outStream.flush();
outStream.close();
}
Can someone please point out the mistake I am making here? I am also trying not to use any third party APIs.
Thanks
You can check this example from JavaPoint.
http://www.javatpoint.com/how-to-write-data-into-PDF-using-servlet
I am not sure that we must use a third party API for this. I am able to achieve this using iText API. Might help someone else.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long logFileId = Long.valueOf(request.getParameter(REQUEST_PARAM_DOCUMENT_ID));
MappingInfo mapping = documentService.getMapping(logFileId);
byte[] file = mapping.getImportLogs();
OutputStream outStream = response.getOutputStream();
Document document = new Document();
try {
PdfWriter.getInstance(document, outStream);
document.open();
document.add(new Paragraph(new String(file)));
document.add(Chunk.NEWLINE);
document.add(new Paragraph("a paragraph"));
} catch (DocumentException e) {
e.printStackTrace();
}
document.close();
response.setContentLength(file.length);
response.setContentType("application/pdf");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=ImportLog.pdf");
response.setHeader(headerKey, headerValue);
outStream.write(file);
outStream.flush();
outStream.close();
}

Converting byte array to PDF and display in JSP page

I am doing a JSP site, where I need to display PDF files.
I have byte array of PDF file by webservice and I need to display that byte array as PDF file in HTML. My question is how to covert that byte array as PDF and display that PDF in new tab.
save these bytes on the disk by using output stream.
FileOutputStream fos = new FileOutputStream(new File(latest.pdf));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
byte[] pdfContent = //your bytes[]
bos.write(pdfContent);
Then send its link to client side to be opened from there.
like http://myexamply.com/files/latest.pdf
better is to use a servlet for this, since you do not want to present some html, but you want to stream an byte[]:
public class PdfStreamingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
public void processRequest(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
// fetch pdf
byte[] pdf = new byte[] {}; // Load PDF byte[] into here
if (pdf != null) {
String contentType = "application/pdf";
byte[] ba1 = new byte[1024];
String fileName = "pdffile.pdf";
// set pdf content
response.setContentType("application/pdf");
// if you want to download instead of opening inline
// response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
// write the content to the output stream
BufferedOutputStream fos1 = new BufferedOutputStream(
response.getOutputStream());
fos1.write(ba1);
fos1.flush();
fos1.close();
}
}
}
Sadly, you do not tell us what technology you use.
With Spring MVC, use #ResponseBody as an annotation for your controller method and simply return the bytes like so:
#ResponseBody
#RequestMapping(value = "/pdf/shopping-list.pdf", produces = "application/pdf", method=RequestMethod.POST)
public byte[] downloadShoppingListPdf() {
return new byte[0];
}
Opening in a new tab is an unrelated matter that has to be handled in the HTML.

Why does my browser receive no data when OutputStream.flush() is called?

I have a servlet which just read a file and send it to the browser.
The file is readen correctly, but on OutputStream.flush(), the browser receive no data.
Firefox says :
"Corrupted Content Error
The page you are trying to view cannot be shown because an error in the data transmission was detected.". Firebug shows the status "Aborted".
IE open or save an empty file.
I tried little or big files.
The code is :
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Use a ServletOutputStream because we may pass binary information
response.reset();
OutputStream out = response.getOutputStream();
// Get the file to view
String file = request.getParameter("path");
// Get and set the type and size of the file
String contentType = getServletContext().getMimeType(file);
response.setContentType(contentType);
long fileSize = (new File(file)).length();
response.setHeader("Content-Length:", "" + fileSize);
File f = new File(file);
response.setHeader("Content-Disposition", "attachment;filename="+f.getName());
response.setContentLength((int) fileSize);
// Return the file
try {
returnFile(file, out, response);
} catch (Exception e) {
Logger.getLogger(AffichageItemsServlet.class).error("", e);
} finally {
out.close();
}
}
// Send the contents of the file to the output stream
public static void returnFile(String filename, OutputStream out, HttpServletResponse resp)
throws FileNotFoundException, IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
byte[] buff = new byte[8* 1024];
int nbRead = 0;
while ((nbRead = fis.read(buff, 0, buff.length)) !=-1) {
out.write(buff, 0, nbRead);
}
out.flush();
} finally {
if (fis != null) {
fis.close();
}
}
}
The response is sent on "out.flush".
Any idea ?
For one thing, remove this line (you call setContentLength() below that):
response.setHeader("Content-Length:", "" + fileSize);
Also, you might try moving the getOutputStream() call to just before you start using the stream.

Categories

Resources