Maro Maro - 2 months ago 16
Java Question

Streaming PDF Opens as text in the browser

I am writing a Filter that streams PDF to the browser. But it is not prompting to open the PDF. What I am getting is the content of the PDF displayed in the browser window as below:

%PDF-1.4 %âãÏÓ 4 0 obj <>stream xKoÂ0ïû+æØJ±CGo<-¤£ªIIIJEüû:Qi9 V¾xvw>ÍÚ{ê+âp-Á\*&_ÑöÄï:'21Ñý- )½¾qÄÔµárÙÌç$¥ÇL÷¢wݵ·´Ô£Wש^¨ÐØæT&Bg$ L¨wmUÀ2á89ºÓÝ8ª¬Ø Å«C®Ó$O0ØEYQYå÷jÛä¿ó,Æ[ïéµDLÊ´@guj`íà .:ÜîOòky#Ü/ªMõÃ_å2Ù:tk¾ôýBµð}eÀÀ,X¨ñ P¾¡ú±zËÁãSo6ÄÔWà?²ë1!Zôs|fÉÉ@QÖ8WzÁ:±.?Îßæçô¾RuÛ endstream endobj 1 0 obj<>>>/MediaBox[0 0 595.28 841.88]>> endobj 3 0 obj<> endobj 2 0 obj<> endobj 5 0 obj<> endobj 6 0 obj<> endobj 7 0 obj<> endobj xref 0 8 0000000000 65535 f


I examined the response headers and they show as below:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename=example.pdf
Connection: keep-alive
Keep-Alive: timeout=5
Accept-Ranges: bytes
Content-Type: application/pdf;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Thu, 13 Oct 2011 01:56:17 GMT

3db
%PDF-1.4
%âãÏÓ
3 0 obj <</Length 145/Filter/FlateDecode>>stream
xœMŽ1Â0…÷÷+ž›.ñ’&M\E‡B ƒ¸U+%µ´‹ßT¨È-÷½û8Þˆ}„0X­B`lpˆ¨0B”Þñ
Ãs¾wЮ7aƒ¢d7û=œÛ)N¥›1«ëÏz¢Æ+¿gjç
Û£¦±Œèoªi
½÷Ê:ÆëÓ=¥õ0¥fµ‰ÝR³ÂÁ¾(V
endstream
endobj
1 0 obj<</Parent 4 0 R/Contents 3 0 R/Type/Page/Resources<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]/Font<</F1 2 0 R>>>>/MediaBox[0 0 595.28 841.88]>>
endobj
2 0 obj<</BaseFont/Times-Bold/Type/Font/Encoding/WinAnsiEncoding/Subtype/Type1>>
endobj
4 0 obj<</Type/Pages/Count 1/Kids[1 0 R]>>
endobj
5 0 obj<</Type/Catalog/Pages 4 0 R>>
endobj
6 0 obj<</Producer(iText 2.0.8 \(by lowagie.com\))/ModDate(D:20111013145617+13'00')/CreationDate(D:20111013145617+13'00')>>
endobj
xref
0 7
0000000000 65535 f
0000000227 00000 n
0000000389 00000 n
0000000015 00000 n
0000000477 00000 n
0000000527 00000 n
0000000571 00000 n
trailer
<</Root 5 0 R/ID [<f6f88fa439f0fb7ffd89bb5bcc013692><d7556c8d673d80e2889958cdface8dba>]/Info 6 0 R/Size 7>>
startxref
702
%%EOF

0


I have tried:


  • Setting the Content-disposition to attachment

  • Without Content-disposition

  • Setting the MIME to application/download

  • Setting The Cache-Control to maxage=1

  • Setting the Pragma to public

  • I have also set the MIME type in the Tomcat web.xml

  • Created a new standard web-app and used the exact same code and it the PDF was generated without a hitch.


Answer

Below are the things that you should make sure is in your Servlet before writing response to outputstream :

res.setContentType( "application/pdf" );
res.setHeader("Content-disposition",
                  "attachment; filename=" +
                  "Example.pdf" );

attachment tag is used to tell that do not open document in browser but with some PDF Reader application (like Adobe Acrobat)

filename is default name of the file to be used.

Comments