由于最近把网页内容生成PDF,页面用的是JSP 只能通过JSP转HTML 然后再通过iText把HTML转PDF
private String jspToHtml(HttpServletRequest request, HttpServletResponse response,List<String[]> list) {
ByteArrayOutputStream os = null;
final PrintWriter pw;
InputStream is = null;
ByteArrayOutputStream os2 = null;
try {
//这里是JSP的路径
String url = "/pages/pdfTemplate.jsp";
RequestDispatcher rd = request.getRequestDispatcher(url);
os = new ByteArrayOutputStream();
pw = new PrintWriter(new OutputStreamWriter(os,
"utf-8"));
HttpServletResponse rep = new HttpServletResponseWrapper(response) {
public PrintWriter getWriter() throws IOException {
return pw;
}
};
request.setAttribute("LIST", list);
rd.include(request, rep);
pw.flush();
is = new ByteArrayInputStream(os.toByteArray());
os2 = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1 ) {
os2.write(buffer, 0, len);
}
os.flush();
os2.flush();
if (pw != null) {
pw.close();
}
return os2.toString("UTF-8");
} catch (Exception e) {
LogUtil.APP.error("转HTML出错!", e);
} finally {
try {
if (os2 != null) {
os2.close();
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (Exception e) {
LogUtil.APP.error("关流出错!", e);
}
}
return null;
}