【java】生成【PDF】后端接口-- java生成PDF的第二步

1. 放置模板

在这里插入图片描述

2. 后端代码

@PostMapping("downloadWord")
    public ResultVO downloadWord(@RequestBody Map map, HttpServletRequest request){
    	//获取数据
        Map<String, Object> dataMap = getDataMap(map);
        //生成文件
        String path = WordUtils.createWord(dataMap,"模板1.ftl", "实施方案模板"+System.currentTimeMillis()+".doc");
        String base64 = WordToPdfUtils.docTopdfBase64(request, path, "项目实施方案" + System.currentTimeMillis() + ".pdf");
        return new ResultVO().addData("base64",base64);
    }

1. 获取数据并封装数据

private Map<String, Object> getDataMap(@RequestBody Map map) {
        //根据统一社会信用代码查询出所有的数据
        String tyshxydm = (String) map.get("tyshxydm");
        Map pxbMap = null;
        
        int page = (int) map.get("page");
        int rows = (int) map.get("rows");
        //查询单位信息
        GyQyxx gyQyxx = gyQyxxService.selectById(tyshxydm);
        //查询培训班信息
        String pxbid = (String) map.get("pxbid");
        GyPxxm gyPxxm = new GyPxxm();
        gyPxxm = gyPxxmService.selectById(pxbid);
        //查询授课教师信息
        List<GyPxxmSkzj> gyPxxmSkzjList = gyPxxmSkzjService.queryList(pxbid, page, rows);
//        List<GyPxxmSkzj> gyPxxmSkzjList =(List) skzjMap.get("list");
        //查询研修内容
        List<GyPxxmYxnr> yxnrList = gyPxxmYxnrService.queryList(pxbid, page, rows);
//        List<GyPxxmYxnr> yxnrList = (List) yxnrMap.get("list");

        //装配数据
        Map<String, Object> dataMap = new HashMap<String, Object>();
//        这是在根据模板中的字段进行值的封装
        dataMap.put("y", gyPxxm.getRkrq().substring(0, 4));
        dataMap.put("m", gyPxxm.getRkrq().substring(4, 6));
        dataMap.put("d", gyPxxm.getRkrq().substring(6, 8));
        dataMap.put("yyxmmc", gyPxxm.getYyxmmc());
        dataMap.put("zymc", gyPxxm.getZymc());
        dataMap.put("yrdwmc", gyQyxx.getYrdwmc());
        dataMap.put("yxbdd", gyPxxm.getYxbdd());
        dataMap.put("xyrs", gyPxxm.getXyrs());
        dataMap.put("xyly", gyPxxm.getXyly());
        dataMap.put("yxmdhzy", gyPxxm.getYxmdhzy());
        dataMap.put("pxtjbzcs", gyPxxm.getPxtjbzcs());
        dataMap.put("yxsxjfys", gyPxxm.getYxsxjfys());
        dataMap.put("pxjgdz", gyPxxm.getPxjgdz());
        dataMap.put("pxjglxr", gyPxxm.getPxjglxr());
        dataMap.put("pxjgbgdh", gyPxxm.getPxjgbgdh());
        dataMap.put("pxjgsj", gyPxxm.getPxjgsj());
        dataMap.put("pxjgcz", gyPxxm.getPxjgcz());
        dataMap.put("pxjgyx", gyPxxm.getPxjgyx());

        List<SkzjWordDTO> gyPxxmSkzjs = new ArrayList();
        List<YxnrWordDTO> gyPxxmYxnrs = new ArrayList<>();

        for (GyPxxmSkzj item : gyPxxmSkzjList) {
            SkzjWordDTO skzjWordDTO = new SkzjWordDTO();
            skzjWordDTO.setSkzjnl(item.getSkzjnl());
            skzjWordDTO.setSkzjxm(item.getSkzjxm());
            skzjWordDTO.setSkzjgzdw(item.getSkzjgzdw());
            skzjWordDTO.setSkzzcjndj(ConstCode.jndjType.get(item.getSkzzcjndj()));
            gyPxxmSkzjs.add(skzjWordDTO);
        }

        dataMap.put("skzj", gyPxxmSkzjs);
        AtomicInteger zks = new AtomicInteger();
        for (GyPxxmYxnr item : yxnrList) {
            YxnrWordDTO yxnrWordDTO = new YxnrWordDTO();
            yxnrWordDTO.setKs(item.getKs());
            yxnrWordDTO.setPxnr(item.getPxnr());
            yxnrWordDTO.setPxxs(item.getPxxs());
            yxnrWordDTO.setSkzjxm(item.getSkzjxm());
            gyPxxmYxnrs.add(yxnrWordDTO);
            int i = Integer.parseInt(item.getKs());
            zks.addAndGet(i);
        }
        dataMap.put("yxnr", gyPxxmYxnrs);
        dataMap.put("zks", zks);
        dataMap.put("jykh", gyPxxm.getJykh());
        return dataMap;
    }

2. 生成word文档

public static String createWord(Map dataMap, String templateName, String fileName) {
        String filePath = null;
        //创建配置实例 
        Configuration configuration = new Configuration(new Version("2.3.28"));
        //设置编码
        configuration.setDefaultEncoding("UTF-8");
        //ftl模板文件
        configuration.setClassForTemplateLoading(WordUtils.class,"/template");
        try {
            String path ="E:/files/";  //本地开发环境
            //获取模板
            Template template = configuration.getTemplate(templateName);
            String fname = fileName;
            File outFile = new File(path+fname);
            filePath = path+fname;
            System.out.println(filePath);
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
            template.process(dataMap, out);
            out.flush();
            out.close();
        }catch (Exception e){
            log.error("导出word文档出错", e);
            throw e;
        }finally {
            return filePath;
        }
    }

3. 将word文档转换为PDF文件(base64)

public static String docTopdfBase64(HttpServletRequest request, String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            log.info("验证License信息:error");
        }
     
        String path ="E:\\files\\";  //本地开发环境
        //上一步生成的Word文档
        outPath = path + outPath; 
        File wordFile = new File(inPath);
        String base64 = null;
        try {
            //开始时间
            long old = System.currentTimeMillis();
            //获取文件
            File file = new File(outPath);
            //获取文件流
            OutputStream fos = new FileOutputStream(file);
            FileInputStream in = new FileInputStream(file);
            // Address是将要被转化的word文档
            Document document = new Document(inPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
            document.save(fos, SaveFormat.PDF);
            //转base64
            byte[] bytes = new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
            in.close();

            //结束时间
            long now = System.currentTimeMillis();
            System.out.println("PDF转换结束 共耗时:" + ((now - old) / 1000.0) + "秒");
            fos.close();
            wordFile.delete();
            file.delete();
        } catch (Exception e) {
            log.info("生成pdf文件流异常");
            e.printStackTrace();
        }
        return base64;
    }

4. 验证License 若不验证则转化出的pdf文档会有水印产生

private static boolean getLicense() {
        boolean result = false;
        try {
            System.out.println(WordToPdfUtils.class.getClassLoader());
            InputStream is = WordToPdfUtils.class.getClassLoader().getResourceAsStream("License.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

5.License.xml (License证书的使用)

<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值