Loading

自定义文档工具(word合并、word转pdf)

自定义文档工具

实现功能:
1、合并多份word文档。
2、word转pdf

实现方法

1、引入依赖。

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.8.2</version>
</dependency>
<!-- documents4j -->
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-local</artifactId>
    <version>1.1.7</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-client</artifactId>
    <version>1.1.7</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-server</artifactId>
    <version>1.1.7</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer-msoffice-word</artifactId>
    <version>1.1.7</version>
</dependency>

2、编码实现

@Component
public class DocUtil {

    /**
     * word后缀
     */
    private static final String WORD_SUFFIX = ".docx";

    /**
     * pdf后缀
     */
    private static final String PDF_SUFFIX = ".pdf";

    /**
     * 文件服务
     */
    @Resource
    private FileCenterService fileCenterService;

    /**
     * 文件工具
     */
    @Resource
    private FileUtil fileUtil;


    /**
     * 合并word文档
     */
    public Map<String, String> mergeDoc(String fileName, boolean isToFdf, String... fileIds) throws Exception {
        String mainWordId;
        HashMap<String, String> map = new HashMap<>();
        if(ObjectUtil.isEmpty(fileIds)){
            BaseCustomExceptionAssert.isTrue(false, "500", "未选择文档!");
        }
        //从文件服务器下载文档
        Response mainResponse = fileCenterService.downloadFile(fileIds[0]);
        NiceXWPFDocument mainDoc;
        //主文档为是空文档
        if(ObjectUtil.equals(mainResponse.body().toString(), StringPool.EMPTY)){
            mainDoc= null;
        }else {
            mainDoc = new NiceXWPFDocument(mainResponse.body().asInputStream());
        }
        for (int i = 1; i < fileIds.length; i++) {
            Response response = fileCenterService.downloadFile(fileIds[i]);
            //空文档不合并
            if(!ObjectUtil.equals(response.body().toString(), StringPool.EMPTY)) {
                if(mainDoc != null) {
                    //分页
                    mainDoc.createParagraph().setPageBreak(true);
                }else{
                    //主文档为空文档
                    mainDoc = new NiceXWPFDocument();
                }
                NiceXWPFDocument otherDoc = new NiceXWPFDocument(response.body().asInputStream());
                mainDoc = mainDoc.merge(otherDoc);
            }
        }
        if(fileIds.length > 1 && mainDoc != null) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            mainDoc.write(outputStream);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            FileItem fileItem = createFileItem(byteArrayInputStream, fileName + WORD_SUFFIX);
            //上传文件到文件服务器,并返回ID
            mainWordId = fileUtil.getFileId(fileItem);
            map.put("fileId", mainWordId);
            byteArrayInputStream.close();
            outputStream.close();
        }
        //只有一份文档,或者所有文档都为空文档
        else{
            mainWordId = fileIds[0];
            map.put("fileId", fileIds[0]);
        }
        //是否转PDF
        if(isToFdf){
            map.put("pdfFileId", wordToPdf(mainWordId, fileName));
        }
        return map;
    }
    /**
     * word转pdf
     * @param fileId word文件ID
     * @param fileName 文件名
     */
    public String wordToPdf(String fileId, String fileName) throws IOException, ResourceException {
        if(ObjectUtil.isEmpty(fileId)){
            throw new ResourceException("word文件异常,转换pdf失败!");
        }
        Response response = fileCenterService.downloadFile(fileId);
        InputStream inputStream = response.body().asInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        IConverter converter = LocalConverter.builder().build();
        converter.convert(inputStream)
                .as(DocumentType.DOCX)
                .to(outputStream)
                .as(DocumentType.PDF)
                .execute();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
        FileItem fileItem = createFileItem(byteArrayInputStream, fileName + PDF_SUFFIX);
        outputStream.close();
        inputStream.close();
        return fileUtil.getFileId(fileItem);
    }


    public  FileItem createFileItem(InputStream inputStream, String fieldName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("file", "text/plain", true, fieldName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            OutputStream os = item.getOutputStream();
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}

tips: documents4j只支持在windows环境下运行

posted @ 2023-04-13 14:58  IamHzc  阅读(220)  评论(0编辑  收藏  举报