根据word模板生成pdf文件

1、首先建一个word,插入一个表格,需要填充的值用${parame}代替

(注意:这里的参数要和java实体类里面的参数对应起来,代码放在下面)

根据word模板生成pdf文件_第1张图片

2、制作完成后另存为xml格式

根据word模板生成pdf文件_第2张图片

3、然后用文本编辑工具打开这个xml文件,复制源码

根据word模板生成pdf文件_第3张图片

4、 打开:https://mp.csdn.net/mp_blog/creation/editor/131155433,在线格式化xml文件

根据word模板生成pdf文件_第4张图片

5、复制到xml文件,然后将名称改为:exam.ftl 。这里后缀名也需要变更,如图

根据word模板生成pdf文件_第5张图片根据word模板生成pdf文件_第6张图片

6、项目目录结构:

根据word模板生成pdf文件_第7张图片

7、OK,模板制作完成开始搞代码,pom.xml文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        3.1.0
         
    
    com.example
    greate
    0.0.1-SNAPSHOT
    greate
    greate
    
        17
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.mysql
            mysql-connector-j
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
        
        
            wiki.xsx
            x-easypdf
            2.9.10
        
        
            com.itextpdf
            itextpdf
            5.4.3
        
        
        
            com.aspose
            aspose-words
            15.8.0
            system
            ${basedir}/lib/aspose-words-15.8.0.jar
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    

8、填充表格的实体类:Exam.java、GradeVo.java
package com.example.greate.model;

import lombok.Data;

@Data
public class GradeVo {
    private String name;
    private String code;
    private int chinese;
    private int mathematics;
    private int english;
    private int synthesize;
    private int information;
    private int total;
}



package com.example.greate.model;

import lombok.Data;
import java.util.List;

@Data
public class Exam {
    private String date;
    private String desc;
    private List gradeList;
}

 9、生成pdf工具类:GeneratePdfUtil.java

package com.example.greate.util;

import com.aspose.words.License;
import com.example.greate.model.Exam;
import com.example.greate.model.GradeVo;
import freemarker.template.Version;
import io.micrometer.common.util.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import freemarker.core.XMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import wiki.xsx.core.pdf.convertor.XEasyPdfConvertor;


public class GeneratePdfUtil {

    private static final Logger log = LogManager.getLogger(GeneratePdfUtil.class);

    public static void main(String[] args) throws IOException {
        GeneratePdfUtil.acceptList();
    }


    /**
     * 高考成绩单
     * @throws IOException
     */
    public static void acceptList() throws IOException {
        
        String fileName = "高考成绩单";
        Exam exam = new Exam();
        List list = new ArrayList<>();
        GradeVo vo1 = new GradeVo();
        vo1.setName("张三");
        vo1.setCode("GK000001");
        vo1.setChinese(100);
        vo1.setMathematics(120);
        vo1.setEnglish(120);
        vo1.setSynthesize(180);
        vo1.setInformation(60);
        vo1.setTotal(580);

        GradeVo vo2 = new GradeVo();
        vo2.setName("李四");
        vo2.setCode("GK000002");
        vo2.setChinese(120);
        vo2.setMathematics(130);
        vo2.setEnglish(125);
        vo2.setSynthesize(180);
        vo2.setInformation(65);
        vo2.setTotal(620);

        list.add(vo1);
        list.add(vo2);
        exam.setDate("2023年06月11日");
        exam.setDesc("省高校招生办");
        exam.setGradeList(list);
        createDocByObj(exam,fileName,"exam.ftl");
    }

    /**
     * 根据模板生成word文档
     *
     * @param obj map中一定要有filePath键值对
     * @param fileName 文件名称
     * @param templates 模板文件
     * @throws IOException
     */
    public static String createDocByObj(Object obj,String fileName,String templates) throws IOException {
        String saveFilePath = "F:\\";
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:templates");
        if (StringUtils.isEmpty(saveFilePath)) {
            throw new IOException("保存文件路径不存在!");
        }
        if (templates == null) {
            throw new IOException("未获取到模板文件,请确认路径是否正确!");
        }
        String ftlName = templates;
        Version v = new Version("2.3.0",true,new Date());
        Configuration configuration = new Configuration(v);
        configuration.setDefaultEncoding("utf-8");
        configuration.setOutputFormat(XMLOutputFormat.INSTANCE);
        configuration.setDirectoryForTemplateLoading(resource.getFile());
        String outFileName = "";
        if(fileName.contains(".doc")){
            outFileName = fileName;
        }else{
            outFileName = fileName+".doc";
        }
        Template t = configuration.getTemplate(ftlName);
        String of = saveFilePath + "/" + outFileName;
        File df = new File(saveFilePath);
        if (!df.exists()) {
            df.mkdir();
        }
        File outFile = new File(of);
        log.info("文件名称:" + outFileName + ",文件路径:" + outFile);
        Writer out = null;
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream(outFile);
            osw = new OutputStreamWriter(fos, "utf-8");
            out = new BufferedWriter(osw);
            t.process(obj, out);
            String  filePath = saveFilePath+outFileName;
            docTransitionPdf(filePath,filePath.replace(".doc",".pdf"));
        } catch (Exception e) {
            log.error("根据模板生成word文档:", e);
        } finally {
            try {
                out.close();
                osw.close();
                fos.close();
                //删除doc文件
                if(outFile.exists()){
                    log.info("删除:{}",outFileName);
                    outFile.delete();
                }
            } catch (Exception e) {
                log.error("关闭文件流异常:",e);
            }
        }
        return saveFilePath+outFileName.replace(".doc",".pdf");
    }



    /**
     * word文档转pdf文件
     * @param Address 要不转化的文档地址
     * @param pdfName pdf名称
     */
    public static void docTransitionPdf(String Address, String pdfName) throws IOException {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return;
        }
        log.info("==XEasyPdfConvertor start");
        XEasyPdfConvertor.toPdf(Address, pdfName);
        log.info("==XEasyPdfConvertor end");
    }

    /**
     * 验证证书
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = GeneratePdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error("获取license失败:", e);
        }
        return result;
    }
}

 10、运行代码,生成pdf文件如图:

根据word模板生成pdf文件_第8张图片

你可能感兴趣的:(pdf,spring,java,ftl,word)