java中freemarker使用ftl模版生成PDF文件

java中freemarker使用ftl模版生成PDF文件,第1张

java中freemarker使用ftl模版生成PDF文件 说明
调用方法生成PDF时,使用的ftl模版,以及字体都是从jar中读取的,无需担心多节点部署
引用jar

    org.freemarker
    freemarker-gae
    2.3.23



    commons-io
    commons-io
    2.6


    com.alibaba
    fastjson
    1.2.76

文件存放路径
// 字体文件
resources/fonts
// 模版文件
resources/templates
代码
import com.lowagie.text.pdf.baseFont;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.Map;

@Component
public class PdfHelper {

    
    private String classpath = getClass().getResource("/").getPath();

    
    private String templatePath = "/templates";

    
    private String templateFileName = "pdf.ftl";

    
    private String imagePath = "/images/";

    
    private String fontPath = "fonts/";

    
    private String font = "simsun.ttc";

    
    private String encoding = "UTF-8";

    @Value("{$file.path}")
    private String filePath;

    
    public void createPDF(Map data, OutputStream out, String templateName) throws Exception {
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        ITextRenderer renderer = new ITextRenderer();
        String simsun = System.getProperty("user.dir") + "/simsun.ttc";
        String arialuni = System.getProperty("user.dir") + "/arialuni.ttf";
        File fondFile = new File(simsun);
        if (!fondFile.exists()) {
            getFondPath();
        }
        // 设置 css中 的字体样式(暂时仅支持宋体和黑体)
        renderer.getFontResolver().addFont(simsun, baseFont.IDENTITY_H, baseFont.NOT_EMBEDDED);
        renderer.getFontResolver().addFont(arialuni, baseFont.IDENTITY_H, baseFont.NOT_EMBEDDED);

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String templateString = getFileData("templates/" + templateName);
        stringLoader.putTemplate("myTemplate", templateString);
        cfg.setTemplateLoader(stringLoader);
        Template tpl = cfg.getTemplate("myTemplate", "utf-8");
        StringWriter writer = new StringWriter();

        // 把null转换成""
        Map dataMap = CommunalTool.objectToMap(data);
        // 将数据输出到html中
        tpl.process(data, writer);
        writer.flush();

        String html = writer.toString();
        // 把html代码传入渲染器中
        renderer.setdocumentFromString(html);
       
        renderer.layout();
        renderer.createPDF(out, false);
        renderer.finishPDF();
        out.flush();
        out.close();

    }

    // 读取jar中的ftl模版文件
    private String getFileData(String path) {
        InputStream stream = getClass().getClassLoader().getResourceAsStream(path);
        // log.info("infile:"+infile);
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String s = null;
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            br.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    
    private String getFondPath() throws IOException {
        String fontPath = System.getProperty("user.dir");
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("fonts/simsun.ttc");
        //在根目录生成一个文件
        File targetFile = new File(fontPath + "/simsun.ttc");
        // //将流转成File格式
        FileUtils.copyInputStreamToFile(inputStream, targetFile);

        InputStream arialuniStream = getClass().getClassLoader().getResourceAsStream("fonts/arialuni.ttf");
        File arialuni = new File(fontPath + "/arialuni.ttf");
        FileUtils.copyInputStreamToFile(arialuniStream, arialuni);
        return fontPath;
    }

    public void setClasspath(String classpath) {
        this.classpath = classpath;
    }


    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }


    public void setTemplateFileName(String templateFileName) {
        this.templateFileName = templateFileName;
    }


    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }


    public void setFontPath(String fontPath) {
        this.fontPath = fontPath;
    }


    public void setFont(String font) {
        this.font = font;
    }


    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

}

工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import org.apache.commons.lang3.StringUtils;
import sun.misc.base64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class CommunalTool {


    
    public static Object objectToData(Object obj, Class beanClass) throws Exception {
        return JSONObject.parseObject(objectToString(obj), beanClass);
    }

    
    public static Map objectToMap(Map map) throws Exception {
        return JSONObject.parseObject(objectToString(map), Map.class);
    }

    
    public static List objectToList(List list) throws Exception {
        return JSONObject.parseObject(objectToString(list), List.class);
    }

    // fistJson 的一个过滤器
    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    static DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private static ValueFilter filter = new ValueFilter() {
        @Override
        public Object process(Object obj, String s, Object v) {
            if (v instanceof Date) {
                return simpleDateFormat.format(v);
            } else {
                if (v == null) {
                    return "";
                } else {
                    return v;
                }
            }
        }
    };

    
    public static String objectToString(Object obj) {
        // JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
        return JSON.toJSONString(obj, filter, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNullStringAsEmpty);
    }

    
    public static String encodebase64Picture(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        String result = new base64Encoder().encode(buffer);
        if (StringUtils.isNotBlank(result)) {
            result = "data:image/png;base64," + result;
        } else {
            result = null;
        }
        return result;
    }

    
    public static String getTransformationDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    
    public static String getTimeDate(Date date) {
        int minte = getMinute(date);
        minte = minte % 5;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date afterDate = new Date(date.getTime() + 300000);
        System.out.println(sdf.format(afterDate));
        return "1";
    }

    
    public static int getMinute(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MINUTE);
    }

    
    public static String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
    public static String getTime(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL);
        return df.format(date).substring(12, 16);
    }

}


ftl模版
电子化模版单个表格



	
	模版
	
	




	
		${name}
		
			
				
					巡视类型:例行巡视					
										


					

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5672524.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存