aspose书签打印

package com.hisign.ilab.controller.fw;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.aspose.words.*;
import com.hisign.common.AsposeUtil;
import com.hisign.common.FileServerService;
import com.hisign.common.HisignQRCode;
import com.hisign.ilab.entity.fw.Dymb;
import com.hisign.ilab.entity.fw.Dysq;
import com.hisign.ilab.service.fw.DymbService;
import com.hisign.ilab.service.fw.DynbsqService;
import com.hisign.ilab.service.fw.DysqService;
import com.hisign.rest.exception.HisignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


@RestController
public class TemplatePrintController {

    // 日志信息
    private final Logger logger = LoggerFactory.getLogger(TemplatePrintController.class);

    @Autowired
    private DymbService dymbService;

    @Autowired
    private DysqService dysqService;

    @Autowired
    private DynbsqService dynbsqService;

    @Autowired
    private FileServerService fileServerService;

    @Value("${fastdfs_server}")
    public String fastdfs_server;


    /**
     * 打印模板
     *
     * @param data 需要填充模板的数据,数据类型为map
     * @return
     */
    @PostMapping("/templatePrint")
    public String templatePrint(@RequestBody Map<String, Object> data, @RequestParam("templateBh") String templateBh, @RequestParam(name = "requestDoc", required = false) Boolean requestDoc) {
        if (data == null) {
            logger.error("填充数据为空!");
        }
        logger.info("打印模板编号为 [{}]", templateBh);
        Dymb dymb = dymbService.getById(templateBh);
        if (dymb == null) {
            throw new HisignException("打印模板编号不存在, 模板编号为 : " + templateBh);
        }
        if (dymb.getMblj() == null) {
            throw new HisignException("当前模板不存在模板路径,模板编号为: " + templateBh);
        }
        //模板对应书签
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("scbj", 0);
        queryMap.put("mbbh", templateBh);
        queryMap.put("orderBy", "sx");
        queryMap.put("sortName", "asc");
        List<Dysq> dysqList = dysqService.query(queryMap);
        try {
            //模板路径
            String mblj = dymb.getMblj();
            //下载书签
            InputStream inputStream = fileServerService.download(mblj);
            //获取Aspose对象
            Document document = new Document(inputStream);
            Set<Map.Entry<String, Object>> dataMap = data.entrySet();
            if (dysqList.size() > 0) {
                for (Dysq dysq : dysqList) {
                    //书签编码
                    String sqbm = dysq.getSqbm();
                    //截取统一前缀 PO_
                    //书签  截取转小写
//                    String sq = sqbm.substring(3, sqbm.length()).toLowerCase().trim();
                    String sq = sqbm.substring(sqbm.indexOf("_") + 1, sqbm.length()).toLowerCase().trim();
                    for (Map.Entry<String, Object> entry : dataMap) {
                        //数据key  避免字典转换的 大写字母
                        String key = entry.getKey().toLowerCase();
                        //字段名 和 书签名
                        if (sq.equals(key)) {
                            //校验数据类型
                            Integer sqlx = dysq.getSqlx();
                            if (sqlx == 1) {
                                //文本
                                AsposeUtil.setTextAtBookmark(document, sqbm, entry.getValue() + "");
                            } else if (sqlx == 2) {
                                // 图片路径值
                                String value = setSignImage(data.get(sq) + "", data.get("bh") + "", true);
                                AsposeUtil.setPictureAtBookmark(document, sqbm, value);
                            } else if (sqlx == 3) {
                                // 图片路径值   // 二维码
                                String value = getImage(data.get(sq) + "", data.get("bh") + "", true);
                                AsposeUtil.setPictureAtBookmark(document, sqbm, value);
                            } else if (sqlx == 4) {
                                //表格书签的数据为map
                                List<Map<String, Object>> tableDataList = (List<Map<String, Object>>) entry.getValue();
                                if (tableDataList == null || tableDataList.size() == 0) {
                                    continue;
                                }
                                //表格起始行数
                                Integer bgqshs = dysq.getBgqshs();
                                //表格起始行数word默认0开始, 表格书签默认从1开始
                                bgqshs = bgqshs - 1;
                                //数据条数,决定表格行数
                                if (tableDataList.size() >= 1) {
                                    //需要复制的行数, 默认表格有一行空数据
                                    int copy = tableDataList.size() - 1;
                                    //表格总行数,到总数据的行数
                                    int end = bgqshs + copy;
                                    //表格行数复制,从起始行到最后行
                                    for (int i = bgqshs; i < end; i++) {
                                        com.aspose.words.DocumentBuilder builder = new com.aspose.words.DocumentBuilder(document);
                                        com.aspose.words.Table tab = document.getFirstSection().getBody().getTables().get(0);
                                        //一行一行进行向下复制
                                        Node deepClone1 = tab.getRows().get(i).deepClone(true);
                                        tab.getRows().insert(i + 1, deepClone1);
                                    }
                                }
                                //表格其实列默认从第一个开始
                                int lie = 0;
                                for (int i = 0; i < tableDataList.size(); i++) {
                                    //表格每一行的数据
                                    Map<String, Object> tableData = tableDataList.get(i);
                                    Set<Map.Entry<String, Object>> entries = tableData.entrySet();
                                    for (Map.Entry<String, Object> table : entries) {
                                        com.aspose.words.DocumentBuilder builder = new com.aspose.words.DocumentBuilder(document);
                                        com.aspose.words.Table tab = document.getFirstSection().getBody().getTables().get(0);
                                        if (tab == null) {
                                            logger.error("此文档中表格不存在!");
                                        }
                                        builder.moveToCell(0, bgqshs, lie, 0);
                                        builder.write(table.getValue() + "");
                                        lie++;
                                    }
                                    //表格行数下移, 列数归零
                                    bgqshs++;
                                    lie = 0;
                                }
                            } else {
                                throw new HisignException("书签类型有误!");
                            }
                        }
                    }
                }
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String saveFormat;
            // 指定输出类型
            if (requestDoc != null && requestDoc) {
                // 保存word格式
                saveFormat = ".doc";
                document.save(bos, SaveFormat.DOC);
            } else {
                // 保存pdf格式
                saveFormat = ".pdf";
                document.save(bos, SaveFormat.PDF);
            }
            String pdfPath = fileServerService.uploadFile(new ByteArrayInputStream(bos.toByteArray()), dymb.getMbmc() + saveFormat);
            // 保存文书
            return pdfPath;
        } catch (Exception e) {
            throw new HisignException("模板打印异常");
        }
    }

    /**
     * 获取图片 , 二维码 条形码
     *
     * @param
     * @throws IOException e
     */
    private String getImage(String path, String id, boolean isAspose) throws IOException {
        String result = "";
        try {
            // 图片路径不为空
            if (StringUtils.isNotEmpty(path) && !path.equals("null")) {
                BufferedInputStream bin = null;
                FileOutputStream out = null;
                String imagepath = null;
	           /* try {

	                String urlPath = fdfsDownServer + path;
	                // 统一资源
	                URL url = new URL(urlPath);
	                logger.info("file path is="+urlPath);
	                // 连接类的父类,抽象类
	                URLConnection urlConnection = url.openConnection();
	                // http的连接类
	                HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
	                // 设置字符编码
	                httpURLConnection.setRequestProperty("Charset", "UTF-8");
	                // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
	                httpURLConnection.connect();
	                bin = new BufferedInputStream(httpURLConnection.getInputStream());
	                String fileType = HttpURLConnection.guessContentTypeFromStream(bin);
	                fileType = fileType.split("/")[1];
	                //生成本地图片路径
	                String binPath = System.getProperty("user.dir");
	                logger.info("binPath=" + binPath);
	                if (binPath.endsWith(File.separator)) {
	                    binPath = binPath.substring(0, binPath.length() - 1);
	                }
	                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");//设置日期格式
	                String appPath = binPath.substring(0, binPath.lastIndexOf(File.separator));
	                String wordImagePath = appPath + File.separator + "webapps"+File.separator+"wordImage"+File.separator+df.format(new Date());
	                logger.info("wordImagePath=" + wordImagePath);
	                File toDir = new File(wordImagePath);
	                if (!toDir.exists()) {
	                    toDir.mkdirs();
	                }

	                imagepath = wordImagePath + File.separator + id + "." + fileType;
	                logger.info("图片路径{}", imagepath);
	                out = new FileOutputStream(new File(imagepath));
	                int size = 0;
	                byte[] buf = new byte[1024];
	                while ((size = bin.read(buf)) != -1) {
	                    out.write(buf, 0, size);
	                }
	                bin.close();
	                out.close();
	            } catch (Exception e) {
	            	e.printStackTrace();
	                logger.error(e.getMessage());
	            } finally {
	                if (bin != null) {
	                    bin.close();
	                }
	                if (out != null) {
	                    out.close();
	                }
	            }*/
                //生成本地图片路径
                String binPath = System.getProperty("user.dir");
                logger.info("binPath=" + binPath);
                if (binPath.endsWith(File.separator)) {
                    binPath = binPath.substring(0, binPath.length() - 1);
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");//设置日期格式
                String appPath = binPath.substring(0, binPath.lastIndexOf(File.separator));
                String wordImagePath = appPath + File.separator + "webapps" + File.separator + "wordImage" + File.separator + df.format(new Date());
                //路径白名单校验,路径特殊符号校验,此处不需要
                //wordImagePath = FileUrlWhiteListUtil.getInstance().filenameFilter(wordImagePath);
                logger.info("wordImagePath=" + wordImagePath);
                File toDir = new File(wordImagePath);
                if (!toDir.exists()) {
                    toDir.mkdirs();
                }

                imagepath = wordImagePath + File.separator + id;
                logger.info("图片路径{}", imagepath);

                imagepath = HisignQRCode.createQrcode(path, 80, 80, "jpg", imagepath, 4);
                logger.info("图片路径{}", imagepath);
                File file = new File(imagepath);
                //linux 下需要加  file://
                imagepath = "file://" + imagepath;
                if (!file.exists()) {
                    //文件下载失败
                    logger.info("文件下载失败,或图片不存在={}", imagepath);
                    result = "";
                } else {
                    if (isAspose) {
                        result = imagepath;
                    } else {
                        result = "[image]" + imagepath + "[/image]";
                    }
                }
            } else {//查询姓名
                logger.info("图片不存在", "");
                result = "";
            }
            logger.info("图片返回值={}", result);
        } catch (Exception e) {
            logger.error("get the image is error", e);
        }
        return result;
    }

    /**
     * 图片类型
     *
     * @param path     图片地址
     * @param id       uuid
     * @param isAspose
     * @return
     * @throws IOException
     */
    private String setSignImage(String path, String id, boolean isAspose) throws IOException {
        String result = "";
        try {
            // 图片路径不为空
            if (StringUtils.isNotEmpty(path) && !path.equals("null")) {
                BufferedInputStream bin = null;
                FileOutputStream out = null;
                String imagepath = null;
                try {
                    //图片完整地址
                    String urlPath = fastdfs_server + "/" + path;
                    // 统一资源
                    URL url = new URL(urlPath);
                    logger.info("file path is : " + urlPath);
                    // 连接类的父类,抽象类
                    URLConnection urlConnection = url.openConnection();
                    // http的连接类
                    HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                    // 设置字符编码
                    httpURLConnection.setRequestProperty("Charset", "UTF-8");
                    // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
                    httpURLConnection.connect();
                    bin = new BufferedInputStream(httpURLConnection.getInputStream());
                    String fileType = HttpURLConnection.guessContentTypeFromStream(bin);
                    fileType = fileType.split("/")[1];
                    //生成本地图片路径
                    String binPath = System.getProperty("user.dir");
                    logger.info("binPath=" + binPath);
                    if (binPath.endsWith(File.separator)) {
                        binPath = binPath.substring(0, binPath.length() - 1);
                    }
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");//设置日期格式
                    String appPath = binPath.substring(0, binPath.lastIndexOf(File.separator));
                    String wordImagePath = appPath + File.separator + "webapps" + File.separator + "wordImage" + File.separator + df.format(new Date());
                    logger.info("wordImagePath=" + wordImagePath);
                    File toDir = new File(wordImagePath);
                    if (!toDir.exists()) {
                        toDir.mkdirs();
                    }
                    imagepath = wordImagePath + File.separator + id + "." + fileType;
                    logger.info("图片路径{}", imagepath);
                    out = new FileOutputStream(new File(imagepath));
                    int size = 0;
                    byte[] buf = new byte[1024];
                    while ((size = bin.read(buf)) != -1) {
                        out.write(buf, 0, size);
                    }
                    bin.close();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                } finally {
                    if (bin != null) {
                        bin.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                }
                File file = new File(imagepath);
                //linux 下需要加  file://
                imagepath = "file://" + imagepath;
                if (!file.exists()) {
                    //文件下载失败
                    logger.info("文件下载失败,或图片不存在={}", imagepath);
                    result = "";
                } else {
                    if (isAspose) {
                        result = imagepath;
                    } else {
                        result = "[image]" + imagepath + "[/image]";
                    }
                }
            } else {//查询姓名
                logger.info("图片不存在", "");
                result = "";
            }
            logger.info("图片返回值={}", result);
        } catch (Exception e) {
            logger.error("get the image is error", e);
        }
        return result;
    }

    //表格打印测试
    @GetMapping("myTest")
    public String testest() throws Exception {
        String path = "D:/code/ilab-root/ilab-service-smms5001/src/main/resources/template/test.docx";
        // String aa = "M00/00/08/rBACZGHeqXiAbUkGAABWAAtdFh4571.doc";
        File file = new File(path);
        FileInputStream inputStream = new FileInputStream(file);
        //获取Aspose对象
        Document document = new Document(inputStream);

        /* 测试数据
        ArrayList<Map<String, Object>> mapList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            HashMap<String, Object> mapData = new HashMap<>();
            mapData.put("bh", i);
            mapData.put("gs", "海鑫" + i);
            mapData.put("sj", "2020年1月" + i + 1 + "日");
            mapData.put("gsdz", "丰台" + i);
            mapList.add(mapData);
        }

        HashMap<String, Object> testMap = new HashMap<>();
        testMap.put("xm", "张三");
        testMap.put("tx", "M00/00/02/rBACZGGzP2-AWOqkAAFopY3iC7c214.jpg");
        testMap.put("jtdz", "中国陕西");
        testMap.put("table", mapList);
        testMap.put("zj", "无");
        testMap.put("ah", "篮球");

        result = smmsServiceFeign.templatePrint(testMap, "9b441f99d9644712ad933661f6cf752b");*/

        //表格数据
        ArrayList<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 4; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("NUM", i);
            map.put("NAME", "张三" + i);
            map.put("AGE", 20 + i);
            map.put("ADDRESS", "北京" + i);
            mapList.add(map);
        }
        //书签
        ArrayList<String> tableList = new ArrayList<>();
        tableList.add("LXDH");
        tableList.add("AIHAO");
        tableList.add("MINZU");
        tableList.add("ZONGJIAO");
        tableList.add("TABLE");
        int size = mapList.size();
        //todo 表中的起止行数, 数据库中定义的
        int HANG = 3;
        //列从第一个开始
        int LIE = 0;

        if (mapList.size() >= 1) {
            // todo  需要新增的行数
            int END = mapList.size() - 1;
            //需要移动的最后一行, 最后一行
            int total = HANG + END;
            //复制行
            for (int i = HANG; i < total; i++) {
                com.aspose.words.DocumentBuilder builder = new com.aspose.words.DocumentBuilder(document);
                com.aspose.words.Table tab = document.getFirstSection().getBody().getTables().get(0);
                //一行一行进行向下复制
                Node deepClone1 = tab.getRows().get(i).deepClone(true);
                tab.getRows().insert(i + 1, deepClone1);
            }
        }


        for (String table : tableList) {
            if (table.equals("LXDH")) {
                AsposeUtil.setTextAtBookmark(document, table, "18566666666" + "");
            } else if (table.equals("AIHAO")) {
                AsposeUtil.setTextAtBookmark(document, table, "篮球" + "");
            } else if (table.equals("MINZU")) {
                AsposeUtil.setTextAtBookmark(document, table, "汉族" + "");
            } else if (table.equals("ZONGJIAO")) {
                AsposeUtil.setTextAtBookmark(document, table, "无" + "");
            } else if (table.equals("TABLE")) {
                //todo   固定列数数据库设置写死
                for (int i = 0; i < mapList.size(); i++) {
                    Set<Map.Entry<String, Object>> entries = mapList.get(i).entrySet();
                    for (Map.Entry<String, Object> entry : entries) {
                        String key = entry.getKey() + "";
                        String value = entry.getValue() + "";
                        com.aspose.words.DocumentBuilder builder = new com.aspose.words.DocumentBuilder(document);
                        com.aspose.words.Table tab = document.getFirstSection().getBody().getTables().get(0);
                        if (null == tab) {
                            System.out.println("当前文档中表格不存在");
                        }
                        builder.moveToCell(0, HANG, LIE, 0);
                        builder.write(entry.getValue() + "");
                        LIE++;
                    }
                    HANG++;
                    LIE = 0;
                }
            }
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 保存pdf格式
        document.save(bos, SaveFormat.PDF);
        String pdfPath = fileServerService.uploadFile(new ByteArrayInputStream(bos.toByteArray()), "test" + ".pdf");
        // 保存文书
        return pdfPath;
    }
}


版权声明:本文为weixin_46649054原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。