最近作了個事情,是要把數據導出到PDF上,我是經過拿到html,而後調用相關jar工具包導出成PDF的,那html又是jsp產生出來的,而後,就是怎麼樣在java中拿到jsp裝入數據後產生的html了,個人代碼以下: html
String url = "/jsp/" + tagPx + ".jsp";
WebContext context = WebContextFactory.get();
ServletContext sc = context.getServletContext();
HttpServletResponse response = context.getHttpServletResponse();
HttpServletRequest request = context.getHttpServletRequest();
RequestDispatcher rd = sc.getRequestDispatcher(url);
ByteArrayOutputStream os = new ByteArrayOutputStream();
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,
Constant.WEB_CHARSET));
HttpServletResponse rep = new HttpServletResponseWrapper(response) {
public PrintWriter getWriter() throws IOException {
return pw;
}
};
request.setAttribute("list", list);
rd.include(request, rep);
pw.flush();
logger.debug("初始JSP輸出html:\n" + os.toString(Constant.WEB_CHARSET)); java
//接下來這段,是轉PDF前對html的格式化處理,是咱們的工具jar裏面成產PDF時對html的要求,和文章題目無關
InputStream is = new ByteArrayInputStream(os.toByteArray());
Tidy tidy = new Tidy();
ByteArrayOutputStream os2 = new ByteArrayOutputStream();
tidy.setXHTML(true); // 設定輸出爲xhtml(還能夠輸出爲xml)
tidy.setCharEncoding(Configuration.UTF8); // 設定編碼以正常轉換中文
tidy.setTidyMark(false); // 不設置它會在輸出的文件中給加條meta信息
tidy.setXmlPi(true); // 讓它加上<?xml version="1.0"?>
tidy.setIndentContent(true); // 縮進,能夠省略,只是讓格式看起來漂亮一些
tidy.parse(is, os2);
os.flush();
String htmlString = os2.toString(Constant.WEB_CHARSET);
os.close();
pw.close();
is.close();
os2.close();
logger.debug("pdf轉換處理後html:\n" + htmlString);
byte[] pdf = pdfManager.htmlToPDF(htmlString, topXleft); app
必定注意我代碼中紅色字部分,在咱們項目內,是UTF-8,並且,紅色字部分是必須的。以前由於沒有紅色字部分,差點被折磨死,由於線下開發時正確了,放到線上導出的PDF就是亂碼。實在汗顏,這個問題折磨我好幾天以後,我才發現了上面紅色字部分的解決辦法,將問題解決掉了。 jsp