PDA

View Full Version : display pdf report directly in jsp



Anonymous
01-24-2003, 10:52 AM
hi


i managed to run the servlet demo to generate and save a pdf report.

but how can i prevent the 'SaveAs' dialog from prompting and forcing me to save? i wish to directly display the pdf in the jsp file.

based on the provided 2 lines,

response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + "unknown.pdf" + "\"");

i tried to comment out the 2nd line so that only the content type is specified. normally, it will display the contents on the browser directly. but it doesnt seem to happen here. instead, i get a blank screen. no errors are encountered.

pls advise.

thanx

yunyee

Anonymous
01-24-2003, 12:00 PM
Hi,

ah, this is funny: Do you use the internet explorer? If yes, then it could be, that the PDF-Plugin-installation is broken on your system. This seems to happen from time to time, reinstalling the Acrobat-Reader should fix this. I don't know any other browser with such behaviour, so ...

Try to load another PDF-File from somewhere, for instance this one:

http://www.lowagie.com/iText/examples/Chap0101.pdf

This example should be loaded in your browser without an save-to dialog popping up. If this works well, your browser installation is ok, and there must be a bug in your JSP. But I bet, your JSP is totally ok :)

Have more fun,
said Thomas

Anonymous
01-24-2003, 12:26 PM
hi Thomas


nope, the pdf-plugin in my IE is not broken.

when i try to load the pdf link provided by you, the hello world pdf is displaying fine within my browser.

im running on Tomcat4.0, and im accessing my servlet thru a href link like:
click here (/test/reportServlet)

something funny is that, if i include back the 2nd line:
response.setHeader("Content-Disposition", "attachment; filename=\"" + "unknown.pdf" + "\"");

i get 3 File Dialog prompts:
1) that says "You have chosen to download a file from this location.
...8D279D8CA3Aetc... from localhost.
and asking to open file from current location or Save to disk

2) if i select "Open this file from its current location", i get a second File Dialog prompt. this time indicating:

reportServlet from localhost

and again asking for my action.

3) if i again select "Open this file from its current location", i get a third File Dialog prompt. this time indicating:

unknown.pdf from localhost

and again asking for my action.

Finally, when i select "Open this file from its current location", the pdf report is displayed.

why is it that 3 prompts are displayed?


just realised that if i left my blank screen on long enuff, i get a popup message saying "A file I/O error has occurred. The file connection timed out."


pls help ...

thanx ...


yunyee

Anonymous
01-24-2003, 03:20 PM
Hi,

at least the PDFServlet works as expected, using Mozilla 1.2 and IE6, as well as in Mozilla 0.98 and KDE3 on Linux. I just removed the Content-Disposition header and verything worked fine.

I use tomcat 4.0.1 standalone.

This is a dump of the response headers returned by the server:

HTTP/1.1 200 OK
Content-Type: application/pdf
Date: Fri, 24 Jan 2003 19:54:18 GMT
Server: Apache Tomcat/4.0.1 (HTTP/1
Connection: close
Content-Type: application/pdf

So some more questions: Which browser do you use? Maybe I can replicate the behaviour then.

where is this sequence from?

...8D279D8CA3Aetc...

Can you post the response headers?

Another thing your could try is to set the Content-Disposition header to type inline:

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

Quote from RFC2183:

2.1 The Inline Disposition Type

A bodypart should be marked `inline' if it is intended to be
displayed automatically upon display of the message. Inline
bodyparts should be presented in the order in which they occur,
subject to the normal semantics of multipart messages.

So this should display the pdf file in the browser window (and does so here). A positive sideeffect is that you can specifiy an optional filename which is used on Save-LinkTarget-As.

Have more fun,
said Thomas

Anonymous
01-24-2003, 08:02 PM
hi


how do i get the dump of the response headers out?

my IE browser is 5.5. i have tried on 5.0 as well.

i have tried with "inline", but the problem is still the same.

the sequence "...8D279D8CA3Aetc..." was actually the sessionid. actually the entire line would have shown my url.
i tried another example, this time my first web page is http://localhost:8080/testenv/example1.jsp

so the first dialog says the file chosen to download is

example1.jsp from localhost

if i choose to save, the file that was saved is actually my example1.jsp.
if i choose to open file from current location, i get the next File Dialog popup.

in the 2nd File Dialog which displays

reportServlet from localhost

if i choose to save, the file that was saved is the unknown.pdf.
if i choose to open file from current location, i get the 3rd File Dialog popup.

only in the 3rd File Dialog displays

unknown.pdf

which i should expect to see during the 1st File Dialog.

is it normal to get this 3 File Dialog prompts even when i'm using the Content-Disposition, attachment thingy??

im suspecting, it's bcos of this 3 sequences that is causing the problem. since i get the File I/O error if i left the browser as it is. maybe it cant find the generated file.

attached are my files.


yunyee

============================================
<html><head><title>Report Test</title>
</head>
<body>
click2 (servlet/reportServlet)
</body></html>

============================================

package com.jrefinery.report.ext.demo;

import com.jrefinery.io.FileUtilities;
import com.jrefinery.report.JFreeReport;
import com.jrefinery.report.ReportInitialisationException;
import com.jrefinery.report.util.Log;
import com.jrefinery.report.targets.pageable.output.PDFOutputTarget;
import com.jrefinery.report.targets.pageable.PageableReportProcessor;
import com.jrefinery.report.demo.IconTableModel;
import com.jrefinery.report.io.ReportGenerator;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.swing.ImageIcon;
import javax.swing.table.TableModel;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
* A Sample HttpServlet to show how JFreeReports can be used in a
* web based environment. POST and GET are handled equal, so it does not
* matter whether you POST or GET the URL for this servlet.
*
* @author Jeevan Sunkersett
*/
public class JFreeReportServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Log.debug("in processRequest..." + getClass());

JFreeReport thisRpt = null;
try
{
thisRpt = createReport();
}
catch (Exception e)
{
Log.debug ("Failed to parse the report" , e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}

response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\"" + "unknown.pdf" + "\"");
// response.setHeader("Content-Disposition", "attachment; filename=\"" + "unknown.pdf" + "\"");
//above line if enabled will pop-Out the browsers "File Download" dialog
//with the standard options: "Open from current location"/ "Save to disk"

ServletOutputStream out = response.getOutputStream();
try
{
PDFOutputTarget target = new PDFOutputTarget(out, new PageFormat(), true);
target.setProperty(PDFOutputTarget.TITLE, "Title");
target.setProperty(PDFOutputTarget.AUTHOR, "Author");
target.open();

PageableReportProcessor proc = new PageableReportProcessor(thisRpt);
proc.setOutputTarget(target);
proc.processReport();

target.close();
}
catch (Exception e)
{
Log.debug ("Failed to create the report", e);
}
}

/**
* parses the report and returns the fully initialized report.
* @return
*/
private JFreeReport createReport() throws ReportInitialisationException
{
URL rptFormat = getClass().getResource("/first.xml");
if (rptFormat == null)
throw new ReportInitialisationException("The report was not found on the classpath");
try
{
JFreeReport thisRpt = ReportGenerator.getInstance().parseReport(rptFormat);
thisRpt.setData(readData()); //NOTE: NULL data cannot be set into the report.
return thisRpt;
}
catch (Exception e)
{
throw new ReportInitialisationException("Creating the report failed", e);
}
}

private TableModel readData() //copied from First.java
{
IconTableModel result = new IconTableModel();
//find the file on the classpath...
//File f = new File("e:\Jeevan\jlfgr-1_0.jar"); //hardcoded the location of the file.

// can this cause trouble? If you get a "unable to find ... " message try to hardcode
// the file as shown above. (? in this case: find a better solution ...)
File f = FileUtilities.findFileOnClassPath("jlfgr-1_0.jar");
if (f == null)
{
Log.debug("Unable to find jlfgr-1_0.jar\n" +
"Unable to load the icons.\n" +
"Please make sure you have the Java Look and Feel Graphics Repository in your classpath.\n" +
"You may download this jar-file from http://developer.java.sun.com/developer/techDocs/hi/repository.");
return result;
}
try
{
ZipFile iconJar = new ZipFile(f);
Enumeration e = iconJar.entries();
while (e.hasMoreElements())
{
ZipEntry ze = (ZipEntry) e.nextElement();
String fullName = ze.getName();
if (fullName.endsWith(".gif"))
{
String category = getCategory(fullName);
String name = getName(fullName);
Image image = getImage(iconJar, ze);
Long bytes = new Long(ze.getSize());
result.addIconEntry(name, category, image, bytes);
}
}
}
catch (IOException e)
{
Log.debug("Unable to load the ICONS");
}
return result;
}

private Image getImage(ZipFile file, ZipEntry entry) //copied from First.java
{
Image result = null;
try
{
InputStream in = new BufferedInputStream(file.getInputStream(entry));
byte[] bytes = new byte[(int) entry.getSize()];
in.read(bytes);
ImageIcon temp = new ImageIcon(bytes);
result = temp.getImage();
}
catch (IOException e)
{
System.out.println(e.toString());
}
return result;
}

private String getCategory(String fullName) //copied from First.java
{
int start = fullName.indexOf("/") + 1;
int end = fullName.lastIndexOf("/");
return fullName.substring(start, end);
}

private String getName(String fullName) //copied from First.java
{
int start = fullName.lastIndexOf("/") + 1;
int end = fullName.indexOf(".");
return fullName.substring(start, end);
}
}

Anonymous
01-24-2003, 09:42 PM
Hi,

this servlet is valid, I uses exactly the same servlet here for testing.

A stupid question:
<quote>

example1.jsp from localhost

if i choose to save, the file that was saved is actually my example1.jsp.
if i choose to open file from current location, i get the next File Dialog popup.

</quote>

Does this mean, that your JSP-Sourcecode is saved to the output of your JSP?

Now I think I'll definitly need a dump of your connection data. Use this class to create the output:

The main method expects 2 parameters, a HTTP-Method and an HTTP-Url to the resource which should be queried.
Use either GET or HEAD as method parameter, PUT is not supported by this Q&D hack.

So

java NetDump GET http://localhost:8080/testenv/example1.jsp

should give you your JSP page and

java NetDump GET http://localhost:8080/testenv/servlet/reportServlet

should dump the request to the PDF-Servlet.

//--------------------------------------------------------------
import com.jrefinery.report.util.Log;

import java.net.URL;
import java.net.Socket;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;

/**
* Date: Jan 25, 2003
* Time: 3:16:02 AM
*
* $Id$
*/

public class NetDump
{
private static class ConnectionInfo
{
private String host;
private int port;
private String uri;

public ConnectionInfo(URL url)
{
host = url.getHost();
port = url.getPort();
if (port == -1)
{
port = url.getDefaultPort();
}

String file = url.getFile();
String query = url.getQuery();
String ref = url.getRef();

uri = file;
if (query != null)
{
uri += "?";
uri += query;
}
if (ref != null)
{
uri += "?";
uri += ref;
}
}

public String getHost()
{
return host;
}

public int getPort()
{
return port;
}

public String getUri()
{
return uri;
}
}

public static void main (String [] args)
throws Exception
{
if (args.length != 2)
{
Log.error ("Need an Method + URL as parameter");
System.exit(1);
}

String method = args[0];
URL url = new URL (args[1]);
if (url.getProtocol().equals("http") == false)
{
Log.error ("The given url must be a HTTP url");
System.exit(1);
}

ConnectionInfo ci = new ConnectionInfo(url);
Log.debug ("Connecting to: " + ci.getHost() + ":" + ci.getPort());
Socket socket = new Socket(ci.getHost(), ci.getPort());
OutputStream out = socket.getOutputStream();
StringBuffer b = new StringBuffer();
b.append(method.toUpperCase());
b.append(" ");
b.append(ci.getUri());
b.append(" HTTP/1.0\n");
b.append("\n");
Log.debug (b.toString());
out.write(b.toString().getBytes());

InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
while (line != null)
{
System.out.println (line);
line = reader.readLine();
}
in.close();

System.exit(0);
}
}
//--------------------------------------------------------------


Have more fun,
said Thomas

Anonymous
01-27-2003, 10:49 AM
hi

yes, my JSP source is saved when i clicked on "save" initially.
but i realised that if i use the following instead, when i clicked on save, it now saves unknown.pdf

response.setHeader("Content-Disposition", "attachment; filename=unknown.pdf");


this is the dump that i have gotten, it looks fine:

although my Content-Disposition is set with attachement, the dump actually show inline. hmmm ...


java NetDump GET http://localhost:8080/testenv/example1.jsp
=============================================
DEBUG: Connecting to: localhost:8080
DEBUG: GET /testenv/example1.jsp HTTP/1.0


HTTP/1.1 200 OK
Content-Type: text/html;ISO-8859-1
Date: Mon, 27 Jan 2003 15:31:58 GMT
Server: Apache Tomcat/4.0.6 (HTTP/1.1 Connector)
Connection: close
Set-Cookie: JSESSIONID=818523A4316B16C2BDB8A86C358F7423;Path=/testenv

<html><head><title>Report Test</title>
</head>
<body>
click2 (servlet/reportServlet)
</body></html>



java NetDump GET http://localhost:8080/testenv/servlet/reportServlet
===================================================

DEBUG: Connecting to: localhost:8080
DEBUG: GET /testenv/servlet/reportServlet HTTP/1.0


HTTP/1.1 200 OK
Content-Type: application/pdf
Date: Mon, 27 Jan 2003 15:47:41 GMT
Content-Disposition: inline; filename="unknown.pdf"
Server: Apache Tomcat/4.0.6 (HTTP/1.1 Connector)
Connection: close
Content-Type: application/pdf

%PDF-1.4
%ᩬå
6 0 obj
<</Filter /FlateDecode
/Length 535
>>
stream

... the pdf output ...

Anonymous
01-27-2003, 02:03 PM
Hi,

the content type of your jsp's reply is incorrect. The content type should be:

Content-Type: text/html; charset=ISO-8859-1

Your pdf-servlet does not seem to be the problem, the server reponse is 100% valid. To be 100% sure, try to enter the servlet's URL in your browsers address field and load the PDF directly. This should open the file in the current browser window.

The report servlet's response has 2 Content-Type header? Why?

Have more fun,
said Thomas

Anonymous
01-27-2003, 02:06 PM
HI,

ok, if the directly entered pdf-file was not opened in the browser, please send me your tomcat configuration (if the configuration was changed).

Have more fun,
said Thomas