Stream linearized PDF from servlet to browser (fast web view) - java

I'm running a web app that provides a servlet. this servlet opens a pdf file from a Network File System and finally streams it to the requesting browser.
All the pdf files are linearized by adobe lifecycle pdf generator and ready for fast web view.
unfortunately, the fast web view does not work. I guess it's a problem of how to open and stream the file in java code and the setting of response header info.
if i deploy a test pdf within my webapp onto the jboss AS and open it directly from the browser by url, the incrementel loading works.
can anyone help me?
Here's the code of my servlet:
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-Disposition",
"inline;filename=" + documentReference);
response.setHeader("Accept-Ranges", "bytes");
File nfsPDF = new File(NFS_DIRECTORY_PATH + documentReference);
FileInputStream fis = new FileInputStream(nfsPDF);
BufferedInputStream bis = new BufferedInputStream(fis);
ServletOutputStream sos = response.getOutputStream();
byte[] buffer = new byte[(int) nfsPDF.length()];
while (true) {
int bytesRead = bis.read(buffer, 0, buffer.length);
if (bytesRead < 0) {
break;
}
sos.write(buffer, 0, bytesRead);
}
sos.flush();
//... closing...

Let's see. You want to send a file in parts, right? Then you should check Range header (HTTP Header) and send only bytes in this range. I'm correct?

I'm not familiar with "PDF fast web view" feature, but in you're code your're first reading the file completely into buffer and then you write it out. The client won't receive anything before the call to sos.flush(). In fact your while loop is obsolete because there will always be just one run.
Maybe you should try to read/write the stuff blockwise.
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = bis.read(buffer, 0, buffer.length);
if (bytesRead < 0) {
break;
}
sos.write(buffer, 0, bytesRead);
sos.flush();
}
sos.flush();

Related

How to save a PDF file from the PDF URL of Orbeon form with Java

I tried to save a PDF document from the PDF URL generated by Orbeon with Java, and always my InputStream is null. When I open this URL in the browser it work well but when I inspect the code I don't find the body of the PDF.
try {
URL urlPDF = new URL(urlPdfOrbeon);
URLConnection connection = urlPDF.openConnection();
InputStream in = connection.getInputStream();
System.out.println(IOUtils.toString(in)) ;
FileOutputStream fos = new FileOutputStream(newFile("yourFile.pdf"));
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
}
The input stream is not null. But it doesn't have any byte to read anymore when you try writing its content to the file. And that's expected, since immediately before, you read everything in the stream by calling
System.out.println(IOUtils.toString(in));
EDIT:
If the input stream actually contains an HTML page asking you to log in, it's probably that you need to be logged in to access this PDF.

Download servlet is very slow

I have written a servlet which will download the file from a server location. In our own INTRAnet the download seems to be very very slow and also when I have the Adobe addon installed in my browser and if I am downloading a PDF file, the Adobe addon will display the progress bar while downloading the PDF but this is not happening in my case! Below is my code! Should I not response it as attachment?
PrintWriter out = response.getWriter();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setIntHeader("Refresh", 1);
response.setHeader("Content-Disposition",
"inline; filename=\"" + fileNameWithExtension
+ "\"");
FileInputStream fileInStream = new FileInputStream(
filePathWithExtension);
BufferedInputStream bufferInStream = new BufferedInputStream(
fileInStream);
int cnt;
while ((cnt = bufferInStream.read()) != -1) {
out.write(cnt);
}
fileInStream.close();
out.close();
Not sure if there is a better way to do. Basically I tried converting one of my dot net code into this Java Servlet. THe current .NET code is very fast compared to this!
This is hosted on Apache Tomcat and the .NET code is hosted on IIS.
Reading and writing a byte at a time is horrifically inefficient. The canonical way to copy a stream in Java is as follows:
byte[] buffer = new byte[8192]; // or more if you like
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
And you should not use a Writer here, use an OutputStream.

Access (.mdb) file corrupted during servlet write to the client

This was originally a part 2 of a different thread, but another use suggested that I separate the part 2 into it's own topic, so here we go. Original thread is here (Original Thread)
I am using Jackcess to create a V2010 mdb file that I need to transfer to a client that will use Access 2013 to open it. Jackcess itself works - V2010 creates a file that Access 2013 can open when the file is FTP'd to the client by a third party software, such as FAR. However, when I try to upload this file to the client through the servlet (as is the goal of this project), Access on the client says "Unrecognized database format "...file name...". This is the code used for upload. Code itself works, file is transferred, has a non-zero size if it's saved - but Access cannot open it.
Note, for content type I also tried vnd.msassess and octed-stream, with same unsuccessful results. Also, I tried closing the db and creating the FileInputStream from the file name, and, as in the example, tried to create FileInputStream by calling mydb.getFile(). No difference.
response.setContentType("application/vnd.ms-access");
String fileName = "SomeFileName.mdb";
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
Database mydb = generateMDBFile();
FileInputStream fis = new FileInputStream(mydb.getFile());
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
Why does this code corrupt the mdb file? This happens every time, regardless of the size (I tried a tiny 2 column/1 row file, and a huge file with 40 columns and 80000 rows)
Thank you!
You forgot to fill the buffer.
Use
// ...
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
// ...

Getting an Image properly from My Java Web Server

I have created a simple HTTP server in Java. When the browser sends a GET request to my web server for a image file, let's say .jpg. Currently my browser does not get the image properly.
Exactly what header fields must be set?
Currently I have Date, Server, Content-type, Content-Length, Connection. I set the length by using:
fin = new FileInputStream(fileName);
contentLength = fin.available();
Content-Type is set to the correct mime-type, so no problem there.
I write the file data using:
public void sendFile (FileInputStream fin, DataOutputStream out)
{
byte[] buffer = new byte[1024];
int bytesRead;
int strCnt = 0;
try
{
int cnt = 0;
while ((bytesRead = fin.read(buffer)) != -1)
{
out.write(buffer, 0, bytesRead);
}
fin.close();
}
catch (IOException ex)
{
}
}
This is what is received by my Chrome Browser
It seems to not download the full content length.
The actual size of the image file is 2.73KB.
If no header fields are missing then what could be causing the problem?
Look likes you do not send all data. Try to add out.flush(); out.close(); before fin.close():
out.flush();
out.close();
fin.close();
I also suggest you to wrap your DataOutputStream into BufferedOutputStream. From my practice it work much more faster comparing to DataOutputStream when writing to hd/network.

Download process is not visible while servlet is downloading pdf

I m using content-disposition to download pdf . When I click the download button, the complete pdf file is downloaded first and then browser shows the dialog box to save the file. I want the browser to show the process of downloading. The following is my servlet code:
String filename = "abc.pdf";
String filepath = "/pdf/" + filename;
resp.setContentType("application/pdf");
resp.addHeader("content-disposition", "attachment; filename=" + filename);
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream(filepath);
System.out.println(is.toString());
int read = 0;
byte[] bytes = new byte[1024];
OutputStream os = resp.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
System.out.println(read);
os.flush();
os.close();
}catch(Exception ex){
logger.error("Exception occurred while downloading pdf -- "+ex.getMessage());
System.out.println(ex.getStackTrace());
}
The progress cannot be determined without knowing the response body's content length beforehand in the client side. To let the client know about the content length, you need to set the Content-Length header in the server side.
Change the line
InputStream is = ctx.getResourceAsStream(filepath);
to
URL resource = ctx.getResource(filepath);
URLConnection connection = resource.openConnection();
response.setContentLength(connection.getContentLength()); // <---
InputStream is = connection.getInputStream();
// ...
Unrelated to the concrete problem, your exception handling is bad. Replace the line
System.out.println(ex.getStackTrace());
by
throw new ServletException(ex);

Categories

Resources