本文主要是介绍struts2 + freemark + itext 导出pdf(基于模板方式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
生成静态页面方法:
private void statHtml(Product product){try{//初始化FreeMarker配置//创建一个Configuration实例cfg = new Configuration();cfg.setDirectoryForTemplateLoading(new File(ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"jsp\\product"));cfg.setEncoding(Locale.getDefault(), "utf-8");//创建模版对象Template t = cfg.getTemplate("look.html");t.setEncoding("utf-8");//生成静态String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"jsp\\product";//在模版上执行插值操作,并输出到制定的输出流中File fileName = new File(path + "\\look1.html");Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));t.process(product, out);out.flush();out.close();}catch(Exception e){e.printStackTrace();}}导出pdf:public String downPdf() throws Exception{ITextRenderer renderer = new ITextRenderer();if(id > 0 && !"".equals(id)){product = productService.modProduct(id);statHtml(product);}String dest = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"jsp\\product";String outputFile =dest+"\\"+ "报告" + ".pdf"; //定义输出文件全名File outFile = new File(outputFile);if (!outFile.exists()) {outFile.getParentFile().mkdirs();}OutputStream os = new FileOutputStream(outputFile);String path = dest+"\\look1.html";String url = new File(path).toURI().toURL().toString();// 解决中文支持问题ITextFontResolver fontResolver = renderer.getFontResolver();fontResolver.addFont(dest +"\\arialuni.ttf", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);renderer.setDocument(url);renderer.layout();renderer.createPDF(os);os.flush();os.close();return SUCCESS;}private InputStream pdfStream; private String pdfName; 给出get,set方法
xml配置:
<action name="downPdf" class="com.mobile.action.product.ProductAction" method="downPdf"><result name="success" type="stream"><param name="contentType">application/pdf; charset=gb2312</param><param name="inputName">pdfStream</param><param name="contentDisposition">attachment; filename="${pdfName}"</param><param name="bufferSize">4096</param></result></action>
html 模板:
<!DOCTYPE html>
<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></meta><style type="text/css">@page {size: A4 landscape;}h1{font-size:16px;text-align:center}table{width:100%;border-collapse:collapse;table-layout:fixed}table th,table td{border:1px solid gray;text-align:center;font-size:12px;padding:3px;font-weight:normal}table.signature td{border:0}p,ul li{line-height:1.5em}span.hl{color:red}#report-item-notes{list-style:none}#report-item-notes ol{list-style:none}</style></head><body style="font-family:'Arial Unicode MS'"> 必须加这个样式,style 样式要写在 head 里面<h1>产品信息</h1><table><tbody><tr><th>产品名称:</th><th>产品价格:</th></tr><tr><td>${productName}</td><td>${productPrice}</td></tr></tbody></table></body>
</html>
这篇关于struts2 + freemark + itext 导出pdf(基于模板方式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!