iText Freemarker模板生成导出PDF及部署到Linux

1.工程结构

iText Freemarker模板生成导出PDF及部署到Linux_第1张图片

2.maven

  
    
		    javax.servlet
		    servlet-api
		    2.5
		    provided
		
		
		       
            com.itextpdf
            itextpdf
            5.5.11
        
        
            com.itextpdf.tool
            xmlworker
            5.5.11
        
        
            com.itextpdf
            itext-asian
            5.2.0
        
        
        
            org.freemarker
            freemarker
            2.3.26-incubating
        
        
            commons-lang
            commons-lang
            2.6
        
  

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 {

        @Override
        public 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 block
            e.printStackTrace();
        }
        Map a = new HashMap();
        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

你可能感兴趣的:(笔记)