Dynamic JSP page transfer PDF output to the page implementation method _jsp programming

Source: Internet
Author: User

Many problems have been encountered in the recent work. Sum up. The main function of this code is to forward a generated JSP page into a PDF output to the page

Need to use Itext

String html = Servletutils.forward (Request,response, "/web-inf/jsp/depot/print/jhd.jsp");
Forward request to JSP, return parsed content instead of output to browser//system.out.println (HTML);
byte[] PDF = pdfutils.html2pdf (HTML);
Response.setcontenttype ("Application/pdf");
Response.setheader ("Content-length", String.valueof (Pdf.length));
Response.setheader ("Connection", "keep-alive");
Response.setheader ("Accept-ranges", "none");
Response.setheader ("X-frame-options", "DENY");
OutputStream out = Response.getoutputstream ();
Out.write (PDF);
Out.flush (); public class Servletutils {/** * This forward method does not output content to the browser after execution, but instead outputs the output to a byte stream and finally returns as a string * @param request * @param response * @p 
Aram SRC * @return */public static string forward (HttpServletRequest request, httpservletresponse response, String src) { try{/*↓↓↓↓↓ reconstructs The response, modifies the output stream object in the response to the byte array ↓↓↓↓↓*/final Bytearrayoutputstream bytearrayoutputstream = new
Bytearrayoutputstream (); Final Servletoutputstream Servletouputstream = new Servletoutputstream () {@Override public void write (iNT B) throws IOException {bytearrayoutputstream.write (b);} @Override public boolean isready () {return false;} @Overrid
e public void Setwritelistener (Writelistener writelistener) {}};
Final PrintWriter printwriter = new PrintWriter (new OutputStreamWriter (Bytearrayoutputstream, "UTF-8")); Response = new Httpservletresponsewrapper (response) {public Servletoutputstream Getoutputstream () {return
Servletouputstream;
Public PrintWriter getwriter () {return printwriter;}}; /*↑↑↑↑↑↑ reconstructs The response, modifies the output stream object in the response, and outputs it to the byte array ↑↑↑↑↑↑*///performs forward operation Request.getrequestdispatcher (SRC). Forward
(Request,response);
Convert the contents of a byte stream too much into a string return new string (Bytearrayoutputstream.tobytearray (), "utf-8");
catch (Exception e) {throw new RuntimeException (e);}}
} Import com.itextpdf.text.*;
Import Com.itextpdf.text.pdf.PdfWriter;
Import Com.itextpdf.tool.xml.Pipeline;
Import Com.itextpdf.tool.xml.XMLWorker;
Import Com.itextpdf.tool.xml.XMLWorkerFontProvider; Import Com.itextpdf.tool.xml.XMLWorkerHelper;
Import com.itextpdf.tool.xml.exceptions.CssResolverException;
Import Com.itextpdf.tool.xml.html.CssAppliers;
Import Com.itextpdf.tool.xml.html.CssAppliersImpl;
Import Com.itextpdf.tool.xml.html.Tags;
Import Com.itextpdf.tool.xml.parser.XMLParser;
Import Com.itextpdf.tool.xml.pipeline.css.CSSResolver;
Import Com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
Import Com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
Import Com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
Import Com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
Import java.io.*; /** * PDF Tool class/public class Pdfutils {/** * converts HTML to PDF, returns PDF file in byte array * @param HTML * @return PDF byte array * @throws IOEXCE ption * @throws documentexception * @throws cssresolverexception/public static byte[] Html2pdf (String html) throws Ioex
Ception, documentexception,cssresolverexception {Document document = new document (PAGESIZE.A4);
Bytearrayoutputstream OS = new Bytearrayoutputstream (); PDFWriter writer = Pdfwriter.getinstAnce (Document,os);
Document.open (); Xmlworkerfontprovider Fontprovider = new Xmlworkerfontprovider () {@Override public Font getfont (string fontname, String E ncoding, float size, int style) {return Super.getfont (FontName = null?)
"Song Body": FontName, encoding, size, style);
}
};
Fontprovider.addfontsubstitute ("Lowagie", "Garamond");
Fontprovider.setuseunicode (TRUE);
Use our font provider and set it to Unicode font style cssappliers cssappliers = new Cssappliersimpl (Fontprovider);
Htmlpipelinecontext htmlcontext = new Htmlpipelinecontext (cssappliers);
Htmlcontext.settagfactory (Tags.gethtmltagprocessorfactory ());
Cssresolver cssresolver = Xmlworkerhelper.getinstance (). Getdefaultcssresolver (True); pipeline<?> Pipeline = new Cssresolverpipeline (cssresolver,new htmlpipeline (Htmlcontext, New Pdfwriterpipeline (
Document,writer)));
Xmlworker worker = new Xmlworker (pipeline, true);
Xmlparser p = new Xmlparser (worker);
P.parse (New InputStreamReader (Html.getbytes ("GBK")));
Document.close (); REturn Os.tobytearray (); }
}

The above is a small set to introduce the dynamic JSP page to the PDF output to the page to achieve the method, I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.