PDF导出的简单实现
程序员文章站
2024-01-04 13:41:10
...
示例代码(竖向):
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream sos = response.getOutputStream();
try {
//在编辑器里生成的html代码需要替换下空格
//String body = contractTemplate.getContent().replace(" ", " ");
String body = "我们在测试PDF生成到处的问题";
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head><body style=\"font-family:'SimSun';\">");
sb.append(body);
sb.append("</body></html>");
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
//SIMSUN.TTC 字体 IDENTITY_H 文字横向显示
fontResolver.addFont(request.getServletContext().getRealPath("SIMSUN.TTC"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString(sb.toString());
renderer.layout();
response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(("aaaatext" + ".pdf").getBytes("utf-8"), "iso8859-1") + "\"");
response.setContentType("application/pdf;charset=UTF-8");
sos = response.getOutputStream();
renderer.createPDF(sos);
sos.flush();
System.out.println("#####################################success##################################");
} catch (Exception e) {
e.printStackTrace();
}finally{
sos.close();
}
}
横向导出请看这位同学的代码:http://reymont.iteye.com/blog/1135535
由于在导出横向、竖向的PDF是时使用的Document有不同的实现。横向的需要实现com.lowagie.text.Document 通过这个
Document document = new Document(PageSize.A4.rotate()); //A4横向
Rectangle rect = new Rectangle(800,600); //自己设置X,Y
而在上面的示例代码中使用的是:org.w3c.dom.Document
/renderer.setDocument(doc, url)
所以无法设置横向,暂时还没有找到解决办法。。。