Get PDF from url and click on clients browser to download

I have PDF files mounted on an external server. I have to access them in my Java Servlet and push them in the clients browser. The PDF file must be loaded directly or open the "SAVE or OPEN" dialog box. This is what I am trying to use in my code, but it couldn't do much.

URL url = new URL("http://www01/manuals/zseries.pdf");
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream in = url.openStream();

int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE]; 
int n =0;
 while ( (n = in.read(chunk)) != -1 ) {
        bais.write(chunk, 0, n);
  }

      

I have tried many ways to do this but have not been able to succeed. I applaud if you have a good way to do this!

+3


source to share


3 answers


When you read data, you get it in your program memory, which is on the server side. To get it in the user's browser, you also need to write everything you read.

Before you start writing, you should include some relevant headings.

  • Indicate that you are sending a PDF file by setting the mime type
  • Set the length of the content.
  • Indicate that the file is for download and not displayed inside the browser.

To set the mime type use

response.setContentType("application/pdf");

      

To set the length of the content, assuming it has the same content length that you get from the url, use:

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
if ( connection.getResponseCode() == 200 ) {
    int contentLength = connection.getContentLength();
    response.setContentLength( contentLength );

      



To indicate that you want to download the file, use:

    response.setHeader( "Content-Disposition", "attachment; filename=\"zseries.pdf\"";

      

(Take care to change the filename to whatever you want in the save dialog)

Finally, get the input stream from the URLConnection just opened, get the output stream of the servlet response, and start reading from one and write to the other:

    InputStream pdfSource = connection.getInputStream();
    OutputStream pdfTarget = response.getOutputStream();

    int FILE_CHUNK_SIZE = 1024 * 4;
    byte[] chunk = new byte[FILE_CHUNK_SIZE]; 
    int n =0;
    while ( (n = pdfSource.read(chunk)) != -1 ) {
        pdfTarget.write(chunk, 0, n);
    }
} // End of if

      

Remember to use try / catch around this, because most of these methods throw IOException

, timeout exceptions, etc. and finally, both streams are closed. Also remember to do something meaningful (like give an error output) if the answer was not 200.

+4


source


You can pass an array of bytes to the client and then use Itext to "stamp" the pdf in the new file. After that, use java.awt.Desktop to access the file.



public static void lauchPdf(byte[] bytes, String fileName) throws DocumentException, IOException{
    PdfReader reader = new PdfReader(bytes);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileName));
    stamper.close();
    Desktop dt = Desktop.getDesktop();
    dt.browse(getFileURI(fileName));
}

      

0


source


You don't have to press anything (I hope you don't, because you really can't). From the point of view of the browser making the request, you can get the PDF from the database, generate it on the fly, or read it from the file system (this is your case). So let's say you have this in your HTML:

<a href="/dl/www01/manuals/zseries.pdf">DOWNLOAD FILE</a>

      

you need to register a servlet for /dl/*

and implement doGet(req, resp)

like this:

public void doGet(
              HttpServletRequest req
            , HttpServletResponse resp
) throws IOException { 

  resp.setContentType("application/pdf");
  response.setHeader("Content-Disposition",
          "attachment; filename=\"" + suggestFilename(req) + "\"");

  // Then copy the stream, for example using IOUtils.copy ...
  // lookup the URL from the bits after /dl/*
  URL url = getURLFromRequest(req);
  InputStream in = url.openConnection().getInputStream();
  IOUtils.copy(in, resp.getOutputStream());
  fin.close();
}

      

IOUtils

from Apache Commons IO (or just write your own while loop)

0


source







All Articles