Printing dynamically created output through JSP in

2019-03-06 08:45发布

问题:

I am printing the report through JSP dynamically by accessing database. I am using Struts Framework and the Java codes are in Action classes. Finally the output is displayed through JSP pages. It is coming nicely on screen but while printing it does not coming properly. I just want to display the report in PDF format instead of JSP -> HTML format or the JSP page should contain a PRINT IN PDF button/link to do the job.

I am using iText to create PDF file in other modules but it is too time consuming. This time I want to capture the JSP output in my page and print in PDF format. How to capture the JSP output in the same JSP page to print in different format?

I was using iTextrenderer but not been able to print. It successfully converts a URL containing HTML file but how to create the InputStream from the JSP output and use in iText Renderer or any other method? Is it possible to do that? Please suggest the solution.

回答1:

I can see what you want to do here. FlyingSaucer/XHTMLRenderer does a good job of HTML > PDF conversion however it does not work by magic: in your case there are quite a few steps involved.

Essentially the steps are:

  1. PDF export Button calls a Struts Action or Servlet passing all params necessary to regenerate the JSP (i.e. as it was originally rendered).

  2. This Action or Servlet has to invoke the JSP (ensuring any required model attributes are set) and write the Response to a String (rather than writing to the standard response).

  3. Pass this String to XHTMLRenderer to generate the PDF.

  4. Stream the btye [] returned by HTMLRenderer to the client.

I have added a complete end-to-end example here using a simple Servlet. However the principles will be the same with Struts2 or any other framework so you should be able to adapt as required.

https://github.com/alanhay/jsp-to-pdf-exporter