動態jsp頁面轉PDF輸出到頁面的實現方法_JSP編程

來源:互聯網
上載者:User

最近工作中遇到不少問題。總結一下。這段代碼主要功能是將一個產生JSP頁面轉寄成PDF輸出到頁面

需要利用ITEXT

String html = ServletUtils.forward(request,response,"/WEB-INF/jsp/depot/print/jhd.jsp"); //轉寄請求到jsp,返回解析之後的內容而不是輸出到瀏覽器//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 {/*** 此forward方法執行完畢之後不會輸出內容到瀏覽器,而是把輸出到位元組流,最後以字串的形式返回* @param request* @param response* @param src* @return*/public static String forward(HttpServletRequest request, HttpServletResponse response, String src) {try{/* ↓↓↓↓↓重新構造response,修改response中的輸出資料流對象,使其輸出到位元組數組↓↓↓↓↓ */final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();final ServletOutputStream servletOuputStream = new ServletOutputStream() {@Overridepublic void write(int b) throws IOException {byteArrayOutputStream.write(b);}@Overridepublic boolean isReady() {return false;}@Overridepublic 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;}};/* ↑↑↑↑↑↑重新構造response,修改response中的輸出資料流對象,使其輸出到位元組數組↑↑↑↑↑↑ *///執行forward操作request.getRequestDispatcher(src).forward(request,response);//把位元組流中的內容太轉為字串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工具類*/public class PDFUtils {/*** 把html轉換成pdf,以位元組數組的形式返回pdf檔案* @param html* @return pdf位元組數組* @throws IOException* @throws DocumentException* @throws CssResolverException*/public static byte[] html2pdf(String html) throws IOException, DocumentException,CssResolverException {Document document = new Document(PageSize.A4);ByteArrayOutputStream os = new ByteArrayOutputStream();PdfWriter writer = PdfWriter.getInstance(document,os);document.open();XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(){@Overridepublic Font getFont(String fontname, String encoding, float size, int style) {return super.getFont(fontname == null ? "宋體" : fontname, encoding, size, style);}};fontProvider.addFontSubstitute("lowagie", "garamond");fontProvider.setUseUnicode(true);//使用我們的字型提供器,並將其設定為unicode字型樣式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(new ByteArrayInputStream(html.getBytes("gbk"))));document.close();return os.toByteArray();}}

以上所述是小編給大家介紹的動態jsp頁面轉PDF輸出到頁面的實現方法,希望對大家有所協助,如果大家有任何疑問歡迎給我留言,小編會及時回複大家的!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.