开发者

How to send a PDF to the browser from a Java webapplication?

I have a java class that generates a PDF file to a folder in my computer. I have managed to connect this class to a link on a web application and when i click this link it generates the pdf and writes it to the folder on my computer. I would want to change this and have the link send the pdf to the browser instead. How can i do this? The class does not use any HttpRequests or similar and the link isnt a hypertex开发者_如何学Ct link atm. Im looking for the most straight forward way to send a pdf to the browser.


/* Java Code */
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=path/to/file.pdf");


i print it (any kind of file) to the response stream from a byte array, inside a servlet

 if(content != null)
                {
                    response.setContentType( "application/octet-stream" );
                                            response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + "\"");
                response.setContentLength(content.length);
                out.write(content);
            }//where content  is byte[] 


You should be able to write the pdf to a stream, you can pass it the output stream from your response.


There are several ways to do that:

  1. Put PDF file on some place available from Web, and then redirect user to URL, which will lead him to PDF file (if your web server supports this). Redirection may be easily done with "Location" HTTP header.

  2. Send PDF file in HTTP response stream. Note, that you will have to set corresponding Mime-type in HTTP header. Implementation depends on web server / web framework you are using in your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜