实现 word 文档 转 pdf

1.首先将doc模板填好参数如${name}   再将它另存为.xml 文件   然后直接将后缀改成.ftl文件

2.需要用到的jar包:aspose-words-15.8.0-jdk16.jar     freemarker-2.3.29.jar

3.工具类

package com.hhh.fund.util;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 生成文书 pdf的工具类
 *
 * @author 3hzwc
 * @date 2019-7-17
 * @update 3hzwc 2019-12-17 代码规范;增加下载文件的方法
 */
public class PdfUtil {
    private static final Logger logger = LoggerFactory.getLogger(PdfUtil.class);

    public static final String SAVE_PATH = "/upload/pdf";

    public static final String IMG_PREFIX = "<w:pict><w:binData w:name=\"wordml://1.png\">";

    public static final String IMG_SUFFIX = "</w:binData><v:shape id=\"图片 1\" o:spid=\"_x0000_s1026\" o:spt=\"75\" alt=\"\" type=\"#_x0000_t75\" style=\"height:100pt;width:100pt;\" filled=\"f\" o:preferrelative=\"t\" stroked=\"f\" coordsize=\"21600,21600\"><v:path/><v:fill on=\"f\" focussize=\"0,0\"/><v:stroke on=\"f\"/><v:imagedata src=\"wordml://1.png\" o:title=\"\"/><o:lock v:ext=\"edit\" aspectratio=\"t\"/></v:shape></w:pict>";


    /**
     * 生成word,填入数据
     *
     * @param templateName 模板名称,放于 resources/tablesTem 下
     * @param dataMap      需要填充的数据
     * @throws Exception 异常
     */
    public static void createWord(String templateName, String docUrl, Map<String, Object> dataMap) throws Exception {
        // Configuration用于读取ftl文件
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");

        // 获取模板所在的路径
        configuration.setClassForTemplateLoading(PdfUtil.class, "/tablesTem");

        // 以utf-8的编码读取ftl文件
        Template t = configuration.getTemplate(templateName + ".ftl", "UTF-8");

        File file = new File(docUrl);
        if (!file.getParentFile().exists()) {
            //创建目录
            if (!file.getParentFile().mkdirs()) {
                logger.info("创建目录失败!" + file.getParentFile().getAbsolutePath());
            }
        }
        Writer out = new PrintWriter(file, "UTF-8");
        // 调用模板对象的process方法生成静态文件。需要两个参数数据集和writer对象。
        t.process(dataMap, out);
        // 关闭writer对象。
        out.flush();
        out.close();
    }

    /**
     * 验证授权
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            if (is != null) {
                aposeLic.setLicense(is);
            } else {
                logger.error("Word转Pdf失败!未找到授权文件license.xml");
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * word转pdf
     *
     * @param docUrl word路径
     * @param pdfUrl pdf路径
     * @return pdf路径
     * @throws Exception 异常
     */
    public static void convertWordToPdf(String docUrl, String pdfUrl) throws Exception {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return;
        }
        FileOutputStream os;
        long old = System.currentTimeMillis();
        // 新建一个空白pdf文档
        File file = new File(pdfUrl);
        if (!file.getParentFile().exists()) {
            //创建目录
            if (!file.getParentFile().mkdirs()) {
                logger.info("创建目录失败!" + file.getParentFile().getAbsolutePath());
            }
        }
        if (!file.exists()) {
            if (!file.createNewFile()) {
                logger.info("创建文件失败!" + file.getAbsolutePath());
            }
        }
        os = new FileOutputStream(file);
        // Address是将要被转化的word文档
        Document doc = new Document(docUrl);
        // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
        doc.save(os, SaveFormat.PDF);
        // EPUB, XPS, SWF 相互转换
        os.close();
        File word = new File(docUrl);
        if (!word.delete()) {
            logger.info("删除word文件失败!" + docUrl);
        }
        long now = System.currentTimeMillis();
        // 转化用时
        System.out.println("word转pdf共耗时:" + ((now - old) / 1000.0) + "");
    }

    /**
     * 生成并下载word文件
     * @param response
     * @param dataMap
     * @param templateName
     * @param fileName
     * @throws Exception
     */
    public static void createAndDownloadWord(HttpServletResponse response, Map<String, Object> dataMap, String templateName, String fileName) throws Exception {
        //Configuration用于读取ftl文件
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("utf-8");

        //获取模板所在的路径
        configuration.setClassForTemplateLoading(PdfUtil.class, "/tablesTem");

        //以utf-8的编码读取ftl文件
        Template t = configuration.getTemplate(templateName+".ftl", "UTF-8");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        String newFileName = URLEncoder.encode(fileName.replace(".",dateFormat.format(new Date())+"."),"UTF-8");

        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("application/msexcel");
        //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-Disposition", "attachment;fileName=" + newFileName);
        Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), Charset.forName("UTF-8")), 10240);
        t.process(dataMap, out);
        out.close();
    }

    public static String getImageStr(String path) {
        //1、校验是否为空
        if(path==null || path.trim().length()<=0){return "";}

        //2、校验文件是否为目录或者是否存在
        File picFile = new File(path);
        if(picFile.isDirectory() || (!picFile.exists())) return "";

        //3、校验是否为图片
        try {
            BufferedImage image = ImageIO.read(picFile);
            if (image == null) {
                return "";
            }
        } catch(IOException ex) {
            ex.printStackTrace();
            return "";
        }

        //4、转换成base64编码
        String imageStr = "";
        try {
            byte[] data = null;
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            imageStr = encoder.encode(data);
        } catch (Exception e) {
            imageStr="";
            e.printStackTrace();
        }

        return imageStr;
    }
}

 

4.实现的具体方法

public String generationsPdf(String id,String path) throws IllegalAccessException, InvocationTargetException {
        InspectionSupervisionBean superviseTestBean = new InspectionSupervisionBean();
        String pdfPath = "";
        try {
            superviseTestBean = this.getById(id);
            if (superviseTestBean != null) {
                Field[] fields = superviseTestBean.getClass().getDeclaredFields();
                Map<String, Object> dataMap = new HashMap<String, Object>();
                //监督抽查日期
                String inspectionDateStr = "";
                if(null != superviseTestBean.getInspectionDateStr() ){
                    inspectionDateStr = superviseTestBean.getInspectionDateStr();
                }
                dataMap.put("inspectionDateStr",inspectionDateStr);

                //建设单位
                String jsName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getJsName())){
                    jsName = superviseTestBean.getJsName();
                }
                dataMap.put("jsName",jsName);
                //项目负责人
                String projectPrincipal = "";
                if(StringUtils.isNotBlank(superviseTestBean.getProjectPrincipal())){
                    projectPrincipal = superviseTestBean.getProjectPrincipal();
                }
                dataMap.put("projectPrincipal",projectPrincipal);
                //施工单位
                String sgName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getSgName())){
                    sgName = superviseTestBean.getSgName();
                }
                dataMap.put("sgName",sgName);
                //项目经理
                String projectManager = "";
                if(StringUtils.isNotBlank(superviseTestBean.getProjectManager())){
                    projectManager = superviseTestBean.getProjectManager();
                }
                dataMap.put("projectManager",projectManager);
                //监理单位
                String jlName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getJlName())){
                    jlName = superviseTestBean.getJlName();
                }
                dataMap.put("jlName",jlName);
                //总监理工程师
                String jlEngineerHeader = "";
                if(StringUtils.isNotBlank(superviseTestBean.getJlEngineerHeader())){
                    jlEngineerHeader = superviseTestBean.getJlEngineerHeader();
                }
                dataMap.put("jlEngineerHeader",jlEngineerHeader);
                //产权单位
                String cqName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getCqName())){
                    cqName = superviseTestBean.getCqName();
                }
                dataMap.put("cqName",cqName);
                // 负责人
                String cqUnitPrincipal = "";
                if(StringUtils.isNotBlank(superviseTestBean.getCqUnitPrincipal())){
                    cqUnitPrincipal = superviseTestBean.getCqUnitPrincipal();
                }
                dataMap.put("cqUnitPrincipal",cqUnitPrincipal);
                //安装(拆卸)单位
                String acName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getAcName())){
                    acName = superviseTestBean.getAcName();
                }
                dataMap.put("acName",acName);
                // 负责人
                String acUnitPrincipal = "";
                if(StringUtils.isNotBlank(superviseTestBean.getAcUnitPrincipal())){
                    acUnitPrincipal = superviseTestBean.getAcUnitPrincipal();
                }
                dataMap.put("acUnitPrincipal",acUnitPrincipal);
                //检测单位
                String jcName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getJcName())){
                    jcName = superviseTestBean.getJcName();
                }
                dataMap.put("jcName",jcName);
                // 负责人
                String jcUnitPrincipal = "";
                if(StringUtils.isNotBlank(superviseTestBean.getJcUnitPrincipal())){
                    jcUnitPrincipal = superviseTestBean.getJcUnitPrincipal();
                }
                dataMap.put("jcUnitPrincipal",jcUnitPrincipal);
                // 工程名称
                String gcName = "";
                if(StringUtils.isNotBlank(superviseTestBean.getGcName())){
                    gcName = superviseTestBean.getGcName();
                }
                dataMap.put("gcName",gcName);
                // 工程地址
                String address = "";
                if(StringUtils.isNotBlank(superviseTestBean.getAddress())){
                    address = superviseTestBean.getAddress();
                }
                dataMap.put("address",address);
                // 抽查内容
                String samplingContent = "";
                if(StringUtils.isNotBlank(superviseTestBean.getSamplingContent())){
                    if ("1".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( ☑安装  □检测  □产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( □租赁 □安装 □检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("2".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  ☑检测  □产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( □租赁 □安装 □检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("3".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  □检测  ☑产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( □租赁 □安装 □检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("4".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  □检测  □产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( ☑租赁 □安装 □检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("5".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  □检测  □产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( □租赁 ☑安装 □检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("6".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  □检测  □产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( □租赁 □安装 ☑检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("7".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  □检测  □产权 )       备案( ☑登记 )");
                        svalue.append("\n现场行为( □租赁 □安装 □检测 □拆卸 )");
                        samplingContent = svalue.toString();
                    } else if ("8".equals(superviseTestBean.getSamplingContent())) {
                        StringBuffer svalue = new StringBuffer();
                        svalue.append("企业( □安装  □检测  □产权 )       备案( □登记 )");
                        svalue.append("\n现场行为( □租赁 □安装 □检测 ☑拆卸 )");
                        samplingContent = svalue.toString();
                    }
                }
                dataMap.put("samplingContent",samplingContent);
                //现场抽查发现的主要问题
                String trouble = "";
                if(StringUtils.isNotBlank(superviseTestBean.getTrouble())){
                    trouble = superviseTestBean.getTrouble();
                }
                dataMap.put("trouble",trouble);
                //处理意见
                String suggestion = "";
                if(StringUtils.isNotBlank(superviseTestBean.getSuggestion())){
                    suggestion = superviseTestBean.getSuggestion();
                }
                dataMap.put("suggestion",suggestion);
                //监督人员
                String supervisor = "";
                if(StringUtils.isNotBlank(superviseTestBean.getSupervisor())){
                    supervisor = superviseTestBean.getSupervisor();
                }
                dataMap.put("supervisor",supervisor);

                //文件存放路径
                pdfPath = path +"/"+ id + ".pdf";
                String wordPath = path +"/"+ id + ".doc";
          
          
          //生成word PdfUtil.createWord(
"jdRecord", wordPath, dataMap);
          //word转pdf PdfUtil.convertWordToPdf(wordPath, pdfPath);
//插入生成的pdf路径 InspectionSupervision inspectionSupervision = inspectionJpaDao.findOne(id); inspectionSupervision.setPdfUrl(pdfPath); inspectionJpaDao.save(inspectionSupervision); } } catch (Exception e) { e.printStackTrace(); } return pdfPath; }

 

posted @ 2020-06-04 15:44  备储小屁孩  阅读(254)  评论(0编辑  收藏  举报