aspose操作书签

package com.hisign.asms.service.common;

import com.aspose.words.*;
import com.hisign.common.Common;
import com.hisign.common.FileServerService;
import com.hisign.rest.exception.HisignException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.List;
import java.util.Map;


@Component
public class AsposeDocumentConvert {
    
    
    // 注册license
    static {
    
    
        String licstr = "<License>\n" +
                "<Data>\n" +
                "<Products>\n" +
                "<Product>Aspose.Total for Java</Product>\n" +
                "<Product>Aspose.Words for Java</Product>\n" +
                "</Products>\n" +
                "<EditionType>Enterprise</EditionType>\n" +
                "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                "<LicenseExpiry>20991231</LicenseExpiry>\n" +
                "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                "</Data>\n" +
                "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                "</License>";
        InputStream inputStream = new ByteArrayInputStream(licstr.getBytes());
        License licobj = new License();
        try {
    
    
            licobj.setLicense(inputStream);
        } catch (Exception e) {
    
    
            throw new RuntimeException("Aspose License注册失败", e);
        }
    }

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

    @Autowired
    private FileServerService fileServerService;

    /**
     * word转换pdf(输入、输出都是标准文件服务器文件路径)
     * !!!
     * 当word中有图片且与文字是嵌入式关系,可能存在转换失败,bug????
     *
     * @return
     */
    public String word2pdf(String docPath) {
    
    
        if (StringUtils.isEmpty(docPath)) {
    
    
            throw new HisignException("目标转换文档为空");
        }
        if (!docPath.startsWith("M00")) {
    
    
            throw new HisignException("目标转换文档非文件服务器标准路径:" + docPath);
        }
        String suffix = docPath.substring(docPath.lastIndexOf("."));
        if (!".doc".equalsIgnoreCase(suffix) && !".docx".equalsIgnoreCase(suffix)) {
    
    
            throw new HisignException("当前文件非word文档:" + docPath);
        }
        File tempFile = new File("public/temp/" + Common.getUUID() + ".pdf");
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
    
    
            Document document = new Document(fileServerService.download(docPath));
            fos = new FileOutputStream(tempFile);
            document.save(fos, SaveFormat.PDF);
            fis = new FileInputStream(tempFile);
            return fileServerService.uploadFile(fis, tempFile.getName());
        } catch (Exception e) {
    
    
            logger.error("word转换pdf失败", e);
            throw new HisignException("word转换pdf失败:" + e.getMessage());
        } finally {
    
    
            if (fos != null) {
    
    
                try {
    
    
                    fos.close();
                } catch (IOException e) {
    
    
                    logger.error(tempFile.getAbsolutePath() + "文件输出流关闭失败");
                }
            }
            if (fis != null) {
    
    
                try {
    
    
                    fis.close();
                } catch (IOException e) {
    
    
                    logger.error(tempFile.getAbsolutePath() + "文件输入流关闭失败");
                }
            }
            // 删除临时文件
            if (!tempFile.delete()) {
    
    
                logger.error(tempFile.getAbsolutePath() + "临时文件删除失败");
            }
        }
    }

    /**
     * @param document
     * @param start    起始行数
     * @param def      默认行数
     * @param data
     */
    public void setTableAtBookmark(Document document, int start, int def, List<Map<String, String>> data) {
    
    
        if (data == null || data.isEmpty()) {
    
    
            logger.warn("表格书签数据为空");
            return;
        }
        if (start < 1 || def < 1) {
    
    
            logger.error("表格书签起始行数或默认行数不正确");
            return;
        }
        // word起始行从0开始(第一行,对应word第0行)
        start = start - 1;
        int copy;
        if ((copy = data.size() - def) > 0) {
    
    
            int end = start + copy;
            // 表格行数复制,从起始行到最后行
            for (int i = start; i < end; i++) {
    
    
                Table tab = document.getFirstSection().getBody().getTables().get(0);
                //一行一行进行向下复制
                Node deepClone = tab.getRows().get(i).deepClone(true);
                tab.getRows().insert(i + 1, deepClone);
            }
        }
        // 数据填充
        int lie = 0;
        for (Map<String, String> obj : data) {
    
    
            for (Map.Entry<String, String> entry : obj.entrySet()) {
    
    
                DocumentBuilder builder = new DocumentBuilder(document);
                Table tab = document.getFirstSection().getBody().getTables().get(0);
                if (tab == null) {
    
    
                    logger.warn("此文档中表格不存在!");
                    return;
                }
                builder.moveToCell(0, start, lie, 0);
                builder.write(entry.getValue());
                lie++;
            }
            //表格行数下移, 列数归零
            start++;
            lie = 0;
        }
    }

    // 文书书签赋值
    public void setTextAtBookmark(Document document, String bookMark, String text) {
    
    
        if (isExistBookmark(document, bookMark)) {
    
    
            try {
    
    
                if (text == null) {
    
    
                    text = "";
                }
                logger.info("文本书签替换,书签名:{},文本值:{}", bookMark, text);
                document.getRange().getBookmarks().get(bookMark).setText(text);
            } catch (Exception e) {
    
    
                logger.error("书签文本赋值失败,书签名:{},书签值:{}", bookMark, text);
            }
        }
    }

    public void writeTextAtBookmark(Document document, String bookMark, String text) {
    
    
        if (isExistBookmark(document, bookMark)) {
    
    
            try {
    
    
                if (text == null) {
    
    
                    text = "";
                }
                logger.info("文本书签替换,书签名:{},文本值:{}", bookMark, text);
                DocumentBuilder builder = new DocumentBuilder(document);
                builder.moveToBookmark(bookMark);
                builder.write(text);
            } catch (Exception e) {
    
    
                logger.error("书签文本赋值失败,书签名:{},书签值:{}", bookMark, text);
            }
        }
    }

    // 图片书签赋值
    public void setPictureAtBookmark(Document document, String bookMark, String picturePath) {
    
    
        if (isExistBookmark(document, bookMark)) {
    
    
            try {
    
    
                logger.info("图片书签替换,书签名:{},图片路径:{}", bookMark, picturePath);
                DocumentBuilder documentBuilder = new DocumentBuilder(document);
                documentBuilder.moveToBookmark(bookMark);
                documentBuilder.insertImage(picturePath);
            } catch (Exception e) {
    
    
                logger.error("书签插入图片失败,书签名:{},图片路径:{}", bookMark, picturePath);
            }
        }
    }

    // 图片书签赋值
    public void setPictureAtBookmark(Document document, String bookMark, String picturePath,double width, double height) {
    
    
        if (isExistBookmark(document, bookMark)) {
    
    
            try {
    
    
                logger.info("图片书签替换,书签名:{},图片路径:{}", bookMark, picturePath);
                DocumentBuilder documentBuilder = new DocumentBuilder(document);
                documentBuilder.moveToBookmark(bookMark);
                documentBuilder.insertImage(picturePath, width, height);
            } catch (Exception e) {
    
    
                logger.error("书签插入图片失败,书签名:{},图片路径:{}", bookMark, picturePath);
            }
        }
    }

    /**
     * 判断书签是否存在
     *
     * @param document
     * @param bookmark 书签
     * @return true:存在,false:不存在
     */
    public boolean isExistBookmark(Document document, String bookmark) {
    
    
        Bookmark mark = document.getRange().getBookmarks().get(bookmark);
        if (mark != null) {
    
    
            return true;
        }
        logger.info("模板不存在此书签:{}", bookmark);
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_46649054/article/details/137243176