TheSagya
TheSagya

Reputation: 45

Problems displaying a PDF from a Servlet

I tried to display a PDF on my HTML page but it is shown. My servlet code:

try {
    String text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);
    document.open();
    document.add(new Paragraph(text));
    document.close();

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentType("application/pdf");
    response.setContentLength(baos.size());
    OutputStream os = response.getOutputStream();
    baos.writeTo(os);
    os.flush();
    os.close();
}
catch(DocumentException e) {
    throw new IOException(e.getMessage());
}

HTML code:

<object id="mypdfobject" type="application/pdf" style="background-color: orange;color: black">
</object>

JavaScript Code:

$.post("../paymailcontroller?uid="+uId,function(pdata){     
         var objectPDF = document.getElementById("mypdfobject");
         objectPDF.data=pdata;
    });

The browser I am using is Google chrome. If I call the page there is no PDF and I have no idea where to look for.

How can I display the created pdf in any browser?

The current output is like this, which is basically the raw PDF:

%PDF-1.4 %���� 2 0 obj <>stream x�+�r �26S�00SI�2P�5�1���BҸ4>>>/Parent 3 0 R/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000333 00000 n 0000000015 00000 n 0000000421 00000 n 0000000176 00000 n 0000000484 00000 n 0000000529 00000 n trailer <]/Root 5 0 R/Size 7>> startxref 659 %%EOF

Upvotes: 0

Views: 1979

Answers (1)

Lonzak
Lonzak

Reputation: 9816

You have to set the content disposition. There are two possibilities:

(1) Show the PDF within the browser

response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\";");

(2) Open a download to download the document

response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\";");

Update: I think your JScript is not right. E.g. do it like this:

$("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + yourserver + path + file+'" type="application/pdf" width="768" height="1024"></object>');

For the rest of the parameters we set the following options:

response.setStatus(HttpServletResponse.SC_OK);
response.setHeader("pragma", "no-cache");
response.setContentType("application/pdf");

Upvotes: 0

Related Questions