最近做了个事情,是要把数据导出到PDF上,我是通过拿到html,然后调用相关jar工具包导出成PDF的,那html又是jsp产生出来的,然后,就是怎么样在java中拿到jsp装入数据后产生的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));
//接下来这段,是转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);
一定注意我代码中红色字部分,在我们项目内,是UTF-8,而且,红色字部分是必须的。之前因为没有红色字部分,差点被折磨死,因为线下开发时正确了,放到线上导出的PDF就是乱码。实在汗颜,这个问题折磨我好几天之后,我才发现了上面红色字部分的解决办法,将问题解决掉了。