本文主要是介绍iText Freemarker模板生成导出PDF及部署到Linux,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.工程结构
2.maven
<dependencies><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.5.11</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><!--freemarker--><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.26-incubating</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency></dependencies>
3 PDFKit.java
package com.servlet;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;import javax.servlet.http.HttpServletResponse;import java.io.*;
import java.nio.charset.Charset;public class PDFKit {public static class AsianFontProvider extends XMLWorkerFontProvider {@Overridepublic Font getFont(final String fontname, String encoding, float size, final int style) {String fntname = fontname;if (fntname == null) {/*使用的windows里的宋体,可将其文件放资源文件中引入*/String classpath = PDFKit.class.getClassLoader().getResource("").getPath();String fontPath =classpath+"fonts/simsun.ttc";fntname = fontPath;}if (size == 0) {size = 4;}System.out.println(fntname);return super.getFont(fntname, encoding, size, style);}}/*** 生成PDF到输出流中(ServletOutputStream用于下载PDF)* @param data 输入到FTL中的数据* @param response HttpServletResponse* @return*/public void exportToResponse(Object data, HttpServletResponse response){try{String classpath = PDFKit.class.getClassLoader().getResource("").getPath();String filePath = classpath + "templates/hello.ftl";String html= FreeMarkerUtil.getContent(filePath,data);System.out.println(html);OutputStream out = null;out = response.getOutputStream();Document document = new Document(PageSize.A4);PdfWriter writer = PdfWriter.getInstance(document, out);convertToPDF(writer,document,html);// out.close();}catch (Exception ex){ex.printStackTrace();}}/*** @description PDF文件生成*/private void convertToPDF(PdfWriter writer,Document document,String htmlString){//获取字体路径document.open();try {XMLWorkerHelper.getInstance().parseXHtml(writer,document,new ByteArrayInputStream(htmlString.getBytes()),XMLWorkerHelper.class.getResourceAsStream("/default.css"),Charset.forName("UTF-8"),new AsianFontProvider());} catch (IOException e) {e.printStackTrace();}finally {document.close();}}}
FreemarkerUtil.java
public static String getContent(String templatePath,Object data){String templateFileName=getTemplateName(templatePath);String templateFilePath=getTemplatePath(templatePath);if(StringUtils.isEmpty(templatePath)){throw new RuntimeException("templatePath can not be empty!");}try{Configuration config = new Configuration(Configuration.VERSION_2_3_25);config.setDefaultEncoding("UTF-8");config.setDirectoryForTemplateLoading(new File(templateFilePath));config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);config.setLogTemplateExceptions(false);Template template = config.getTemplate(templateFileName);StringWriter writer = new StringWriter();template.process(data, writer);writer.flush();String html = writer.toString();return html;}catch (Exception ex){throw new RuntimeException("FreeMarkerUtil process fail",ex);}}
DownloadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PDFKit kit=new PDFKit();String fileName = "广西XXXX系统健康状况.pdf";response.setContentType("application/pdf");try {response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}Map<String,String> a = new HashMap<String,String>();a.put("name", "中文字符");kit.exportToResponse(a,response);}
参考以下资料
http://blog.csdn.net/zxz547388910/article/details/74315277
ITEXT5.5.8转html为pdf文档解决linux不显示中文问题
https://segmentfault.com/a/1190000009160184
java根据模板动态生成PDF
http://blog.csdn.net/jys1109/article/details/10066747
使用itext将html生成pdf中文换行问题解决方案2
这篇关于iText Freemarker模板生成导出PDF及部署到Linux的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!