JSP转PDF(字节流方式)

public static String forward(HttpServletRequest request, HttpServletResponse response, String address) {

try {
//定义字节流
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//重写servletOuputStream输出流 为字节流
final ServletOutputStream servletOuputStream = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
byteArrayOutputStream.write(b);
}
};
//装饰打印流
final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream, "UTF-8"));

//重写response输出 皆为字节流
response = new HttpServletResponseWrapper(response) {
public ServletOutputStream getOutputStream() {
return servletOuputStream;
}
public PrintWriter getWriter() {
return printWriter;
}
};

//执行forward操作,使返回结果写字节流数组中
request.getRequestDispatcher(address).forward(request, response);

//将字节流中的内容太转为字符串 为jsp转成的html,藉由html转pdf工具进行文件生成
return new String(byteArrayOutputStream.toByteArray(), "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}

运用示例:

posted @ 2020-06-16 11:03  Sublamb  阅读(709)  评论(0)    收藏  举报