Solved

Java setResponseType and PDF files

Posted on 2001-07-12
12
8,432 Views
Last Modified: 2013-11-24
I am using a PDF generation library by the ame of iText: http://www.lowagie.com/iText/

What I am trying to do is generate the PDF document to a servlets output stream, thus going directly to the browser window without being stored on disk.

I wanted to know if anybody out there has experienced this.

My code is as follows (DownloadPDF.jsp):

<%@ page contentType="application/pdf" %>
<%
  try {
    // Create the document
    com.lowagie.text.Document document = new com.lowagie.text.Document(com.lowagie.text.PageSize.A4, 10, 10, 10, 36);
    ServletOutputStream outs = response.getOutputStream();
    com.lowagie.text.pdf.PdfWriter.getInstance(document, outs);
 
    // Open the document
    document.open();
   
    // Add some text to document
    document.add(new com.lowagie.text.Paragraph("Hello World!"));
   
    // Close the document
    document.close();
    outs.close();
  }
  catch (Exception ex) {
    out.println("An exception has occurred: " + ex.toString());
  }
%>

Thank you

Soroush

0
Comment
Question by:Soroush
  • 5
  • 3
  • 2
  • +2
12 Comments
 
LVL 18

Expert Comment

by:bobbit31
ID: 6277773
listening...
0
 

Author Comment

by:Soroush
ID: 6277801
Sorry, the whole point was that all IE5.5 did was load Acrobat and then display a white screen in the IE window. You cannot view source, or save/save as from the file menu. When vieing the properties from the file menu it says that its an Adobe Acrobat File.

No matter what I try I cant get the actual file to display on screen.
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6278529
Hi,

I'm not a JSP/Servlet expert, so can easily be wrong. It seems that you shouldn't close outs, just flush it or use Responce specific method to flush buffer. BTW, I wouldn't use JSP for such taks, Servlet would not require much more work.

Regards,
Igor Bazarny
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 3

Expert Comment

by:superschlonz
ID: 6278645
You could make a zip file with the pdf file in it.
0
 
LVL 4

Accepted Solution

by:
sdussinger earned 200 total points
ID: 6278808
It turns out that closing the response output stream is not the best thing to do.  The problem is actually two-fold. In your code you're closing the output stream yourself explicitly. In addition, according to the documentation for lowagie's iText, the document.close () method also closes the streams that were associated with all of the document's writers.  Therefore, when you close the document, the response output stream is getting closed, anyway.

I got around this problem by using a temporary output stream (a ByteArrayOutputStream) for iText to write into. Once the document is closed, we can write out the bytes in the ByteArrayOutputStream to the actual response output stream.

Since I'm not expert in JSPs, I've implemented a small test program as an HttpServlet. The body of the doGet method should be usable in the body of your JSP, as long as you import the appropriate jar files into your page.

------------Code Snippet ---------------------------------
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.lowagie.text.*;
import com.lowagie.text.html.*;
import com.lowagie.text.pdf.*;

public class PDFServlet extends HttpServlet {

    public void doGet(HttpServletRequest req,
              HttpServletResponse res) throws IOException, ServletException {
        // Specify content type.
        res.setContentType("application/pdf");
        // Access the output stream.
        ByteArrayOutputStream out = new ByteArrayOutputStream ();
        // Return PDF File.

    Document document = new Document (PageSize.A4, 50,50,50,50);

    try {
        // Create the PDF Writer instance
        // Notice that we're actually writing to a temporary
        // ByteArrayOutputStream here. That way when iText
        // closes the stream, we don't have problems. We can still
        // extract the bytes written to the temporary stream and write
        // them to the actual response output stream...
        PdfWriter.getInstance(document, out);

        // Open the document and add some text to it.
        document.open();
        document.add(new Paragraph("Hello world. This is a test."));
    }
    catch(DocumentException de) {
        System.err.println(de.getMessage());
    }

    // Close the document. This also closes the PDFWriter's output stream
    // which is currently pointing to our temporary ByteArrayOutputStream.
    document.close();

    // Now, we can get the bytes written into the ByteArrayOutputStream
    // and write them out to the response output stream.
    res.getOutputStream ().write (out.toByteArray ());
    }

}

------------- End of Code Snippet ------------------------

Hopefully this will solve your problem...

--Steve
0
 

Author Comment

by:Soroush
ID: 6279954
That is fantastic! Thank you very much.

Soroush
0
 
LVL 18

Expert Comment

by:bobbit31
ID: 6281054
Steve -- i copied your above code and all i get is a white screen... any ideas?  I'll post a question to give you points if you can help...

thanks
0
 

Author Comment

by:Soroush
ID: 6281091
My version used a JSP with very similiar code to the above. I have now found that when putting just a table on the PDF page, sometimes a white screen is all I get.
0
 
LVL 4

Expert Comment

by:sdussinger
ID: 6281100
Are you getting the acrobat reader when you connect to the servlet? Or are you just getting a blank screen from your browser? What browser are you using?

Send me some details and I'll see what I can do...
0
 
LVL 18

Expert Comment

by:bobbit31
ID: 6281113
blank screen... ie 5

i'm running apache and tomcat...  I think the problem is i have to set up apache to byte serve pdf files.  But i don't know how. ;)
0
 
LVL 18

Expert Comment

by:bobbit31
ID: 6281263
0
 
LVL 18

Expert Comment

by:bobbit31
ID: 6281328
Actually, forget it, i figured it out...

it's a bug with the i.e. plugin... all i have to do is set the bytearray size.

however, thanks for the help, i'll post a question entitled 'points for sdussinger'
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
simple java question 3 55
maven project error 5 54
Tomcat: Unable to run tomcat service. 2 18
Facing this issue for maven proxy setting 2 9
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to implement Singleton Design Pattern in Java.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question