Take the 2-minute tour ×

I have yer typical servlet that streams a pdf to a browser. The pdfs are stored on an internal server from which my servlet fetches. If I hit the servlet directly from the browser, the pdf is displayed. If I try the same URL in an <IMG> tag in a web page, ... broken pipe.

Any insight on why this should be?

As an experiment, I can stream gifs without issue.

Here's the code which I pretty much scavenged from the innerwebs:

public class PdfServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(PdfServlet.class.getName());

    public void doGet(HttpServletRequest req, HttpServletResponse res) {

        String url = (String) req.getParameter("url");

        log.info("The URL is " + url);
        String format = "application/pdf";
//           String format = "image/gif";

        streamBinaryData(url, format, res);


     * This Method Handles streaming Binary data
     * <p>
     * @param String urlstr ex: http;//localhost/test.pdf etc.
     * @param String format ex: pdf or audio_wav or msdocuments etc.
     * @param ServletOutputStream outstr
     * @param HttpServletResponse resp
    private void streamBinaryData(
            String urlstr,
            String format,
            HttpServletResponse resp) {

        ServletOutputStream outstr = null;
        String ErrorStr = null;

        try {
            outstr = resp.getOutputStream();

            //find the right MIME type and set it as contenttype
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                URL url = new URL(urlstr);
                URLConnection urlc = url.openConnection();
                int length = urlc.getContentLength();

//                resp.setHeader("Content-Length", String.valueOf(+length));
//                resp.setHeader("Content-Disposition", "inline");

                // Use Buffered Stream for reading/writing.
                InputStream in = urlc.getInputStream();
                bis = new BufferedInputStream(in);
                bos = new BufferedOutputStream(outstr);
                byte[] buff = new byte[length];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    log.info("Got a chunk of " + bytesRead);
                    bos.write(buff, 0, bytesRead);
            } catch (Exception e) {
                ErrorStr = "Error Streaming the Data";
            } finally {
                if (bis != null) {
                if (bos != null) {
                if (outstr != null) {
        } catch (Exception e) {

...and the HTML file. The pdf fails with a broken pipe and the gif image is displayed even though the content type is being returned as 'application/pdf'.

        <title>Cheesy Servlet Experiment</title>
        <h1>Cheesy Servlet Experiment</h1>

            <img src="" alt="yah mon">

Edit - the following works in FF. I don't know how standard it is.

<object data="http://www.samplepdf.com/sample.pdf" type="application/pdf" width="600" height="600">
    alt : <a href="http://www.samplepdf.com/sample.pdf">test.pdf</a>

Interesting info here. Looks reasonably well supported.

share|improve this question
edit with possible solution in the posting. –  Tony Ennis Oct 6 '10 at 6:32
What's the functional requirement? Display a PDF inline? Either an <object> or <iframe> is the normal approach for this. –  BalusC Oct 6 '10 at 12:10
At this point I think the requirement is for something to work, lol. The server with the PDFs is behind our firewall. When it was tested, the tester was apparently was still on the VPN or had a cached page. We don't know. But none of our customers can see their PDFs and things are... tense. We pushed to prod on Saturday. –  Tony Ennis Oct 6 '10 at 12:17
add comment

4 Answers

up vote 3 down vote accepted

Can your browser even display PDF files in img elements? That's really unlikely. I think the browser ends the connection when it finds out that it's actually not an image.

Some browsers don't complain about content-types. They check the image file and figure out which format the image is in by itself. That can explain why your GIF image is displayed.

share|improve this answer
I never would have thought of that. –  Tony Ennis Oct 6 '10 at 5:58
add comment

The problem is that you are trying to display a PDF document with the img Tag. img can handle only simple image formats like JPEG, GIF or PNG.

Usually the plain browser is not able to display PDF content on its own. If there is no PDF viewer plugin installed then the browser will only show a save dialog to download the PDF file.

So the safest way would be that your HTML page only contains a link to your PDF file. Maybe with a target="_blank" to open a new browser window.

share|improve this answer
add comment

you should use an anchor tag (if you have to use an img, have an A wrap the IMG with the IMG's src pointing to a real image). The href of the anchor will be your servelt that displays PDFs. make suer you set the right content-type in the servlet.

share|improve this answer
Not quite what I had in mind, but it works. –  Tony Ennis Oct 6 '10 at 5:55
add comment

First thing: you are trying to read length at once. this is not a good practice as it doent assure you of the task

try reading smaller chunks by byte [] read_buffer = new byte[1024 * 10] This way u read 10kb at once.

And write those 10kb on bos.

Keep this loop until you get -1 by the read function.

And yes. You shoud not use img tag for pdf

share|improve this answer
add comment

Your Answer


