Java读取Word关键字工具类及Word填充并转为PDF

798 阅读1分钟

读取Word关键字

public static List<String> getWordKey(String templateUri) {
    String buffer = "";
    List<String> keyListFromString = null;
    String localPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(templateUri, "/profile");
    try {
        OPCPackage opcPackage = POIXMLDocument.openPackage(localPath);
        POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
        buffer = extractor.getText();
        keyListFromString = getKeyListFromString(buffer, "{{", "}}");
        opcPackage.close();
        return keyListFromString;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return keyListFromString;
}

/**
 * 查询一个字符串再另一个字符串中出现的下标
 *
 * @param str
 * @param key
 * @return
 */
public static List<Integer> searchAllIndex(String str, String key) {
    List<Integer> allIndex = new ArrayList<Integer>();
    int a = str.indexOf(key);
    while (a != -1) {
        allIndex.add(a);
        a = str.indexOf(key, a + 1);
    }
    return allIndex;
}

/**
 * 根据关键字 获取字符串中参数
 *
 * @param string
 * @param keyStart 如'${ * @param keyEnd 如 }'
 * @return
 */
public static List<String> getKeyListFromString(String string, String keyStart, String keyEnd) {
    // 返回数据
    List<String> allStringList = new ArrayList<String>();
    // 判断不为空
    if (StringUtils.isNotBlank(string)) {
        string = string.replaceAll("\\\\s*", "");
        // 开始keyIndex集合
        List<Integer> firstIndex = searchAllIndex(string, keyStart);
        // 结束keyIndex集合
        List<Integer> endIndex = searchAllIndex(string, keyEnd);
        // 不为空
        if (CollectionUtils.isNotEmpty(firstIndex)) {
            // 循环
            for (int i = 0; i < firstIndex.size(); i++) {
                // 截取关键字部分
                String temp = string.substring(firstIndex.get(i) + keyStart.length(), endIndex.get(i));
                // 添加到返回数据中
                allStringList.add(temp);
            }
        }
    }
    return allStringList;
}

Word填充并转为PDF

package com.norm.common.util;

import cn.afterturn.easypoi.cache.manager.FileLoaderImpl;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.norm.common.config.RuoYiConfig;
import com.norm.common.utils.DateUtils;
import com.norm.common.utils.StringUtils;
import com.norm.common.utils.uuid.IdUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

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

/**
 * Word文件处理工具类
 *
 * @author gluoh
 */
@Slf4j
public class WordExportUtils {

    /**
     * word填充 - easy poi
     */
    @SneakyThrows
    public static String wordFill(Map<String, Object> map, String templateUrl) {

        XWPFDocument doc = WordExportUtil.exportWord07(templateUrl, map);

        String docxFileName = extractFileName("docx");
        File docxFile = getAbsoluteFile(docxFileName);
        FileOutputStream fos = new FileOutputStream(docxFile);

        doc.write(fos);
        fos.close();

        return getPathFileName(NormConfig.getProfile(), docxFileName);
    }
    
    /**
     * word转为pdf - documents4j
     */
    public static void docx2pdfByDocuments4j(InputStream inputWord) {
        try {
            InputStream docxInputStream = inputWord;
            String pdfName = extractFileName("pdf");
            File desc = getAbsoluteFile(pdfName);
            OutputStream outputStream = new FileOutputStream(desc);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] getFile(String url) {
        InputStream fileis = null;
        ByteArrayOutputStream baos = null;

        try {
            if (url.startsWith("http")) {
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30000);
                urlConnection.setReadTimeout(60000);
                urlConnection.setDoInput(true);
                fileis = urlConnection.getInputStream();
            } else {
                try {
                    fileis = new FileInputStream(url);
                } catch (FileNotFoundException var11) {
                    fileis = FileLoaderImpl.class.getClassLoader().getResourceAsStream(url);
                }
            }

            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];

            int len;
            while ((len = ((InputStream) fileis).read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }

            baos.flush();
            byte[] var6 = baos.toByteArray();
            return var6;
        } catch (Exception var12) {
            log.error(var12.getMessage(), var12);
        } finally {
            IOUtils.closeQuietly((Closeable) fileis);
            IOUtils.closeQuietly(baos);
        }

        log.error(fileis + "这个路径文件没有找到,请查询");
        return null;
    }

    private static String extractFileName(String suffix) {
        String fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + suffix;
        return fileName;
    }

    @SneakyThrows
    private static final File getAbsoluteFile(String fileName) {
        String uploadDir = NormConfig.getProfile();
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd");


    private static final String getPathFileName(String uploadDir, String fileName) {
        int dirLastIndex = NormConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        String pathFileName = "/profile" + currentDir + "/" + fileName;
        return pathFileName;
    }
    
}

所需依赖

<!-- easy poi -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.3.0</version>
</dependency>

<!-- word convert PDF documents4j -->
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-local</artifactId>
    <version>1.0.3</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer-msoffice-word</artifactId>
    <version>1.0.3</version>
</dependency>