offoce转pdf文件预览,基于aspose-cad,aspose-cells,aspose-words,aspose-slides实现word,xls,ppt,dwg转pdf文件预览

之前基于openoffice做过文件转换预览,由于openoffice需要在容器安装服务而且不稳定,
容易因为内存问题,网络问题被挤掉或者无法连接和超时所有换aspose实现.

word,xls,ppt,dwg工具类

package com.ruifu.conversions.utils;

import com.aspose.cad.Color;
import com.aspose.cad.Image;
import com.aspose.cad.imageoptions.CadRasterizationOptions;
import com.aspose.cad.imageoptions.PdfOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
public class DwgToPdfUtil {

    public static File Dwg2Pdf(File dwgFile) throws IOException {
        FileInputStream fileInputStream;
        //将dwg文件转换成InputStream输入流
        fileInputStream = new FileInputStream(dwgFile);

        Image objImage = Image.load(fileInputStream);

        CadRasterizationOptions rasterizationOptions = new  CadRasterizationOptions();

        //设置颜色
        rasterizationOptions.setBackgroundColor(Color.getBlack());
        rasterizationOptions.setPageWidth(1400);
        rasterizationOptions.setPageHeight(650);
        rasterizationOptions.setAutomaticLayoutsScaling(true);
        rasterizationOptions.setNoScaling (false);
        rasterizationOptions.setDrawType(1);

        PdfOptions pdfOptions = new PdfOptions();
        pdfOptions.setVectorRasterizationOptions(rasterizationOptions);

        //输出文件
        File outputFile = new File(dwgFile.getName().substring(0,dwgFile.getName().lastIndexOf("."))+".pdf");
        //存放地址
        try {
            objImage.save(outputFile.getPath(), pdfOptions);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("dwg转pdf失败{}",dwgFile.getName());
        } finally {
            fileInputStream.close();
        }
        log.info("文件转换成功{}",dwgFile.getName());
        return outputFile;
    }
}
package com.ruifu.conversions.utils;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import lombok.extern.slf4j.Slf4j;

import java.io.*;


@Slf4j
public class ExcelToPdfUtil {
    /**
     * 获取license 去除水印
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = ExcelToPdfUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * excel转pdf
     * @param bytes
     * @return
     * @throws IOException
     */
    public static byte[] excel2pdf(byte[] bytes) throws IOException {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return null;
        }
        ByteArrayOutputStream pdfstream=null;
        try {
            // 原始excel流
            Workbook wb = new Workbook(new ByteArrayInputStream(bytes));
            //保存转成pdf的流
            pdfstream = new ByteArrayOutputStream();
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            //缩放到一个页面(如果列太多 太长)设置每张一页
            pdfSaveOptions.setOnePagePerSheet(true);
            wb.save(pdfstream, pdfSaveOptions);
            byte[] outbytes = pdfstream.toByteArray();
            return outbytes;
        } catch (Exception e) {
            log.error("excel转pdf失败");
            return null;
        }finally {
            if (pdfstream!=null){
                pdfstream.close();
            }
        }
    }
}
package com.ruifu.conversions.utils;

import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.*;


@Slf4j
public class PptToPdfUtil {
    public static File ppt2pdf(File pptFile) throws IOException {
        //输出文件
        File outputFile = new File(pptFile.getName().substring(0,pptFile.getName().lastIndexOf("."))+".pdf");
        //输入文件
        FileInputStream fileInputStream = new FileInputStream(pptFile);
        Presentation pres = new Presentation(fileInputStream);
        try {
            pres.save(outputFile.getPath(), SaveFormat.Pdf);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ppt转pdf失败{}",pptFile.getName());
        } finally {
            fileInputStream.close();
        }
        return outputFile;
    }
}
package com.ruifu.conversions.utils;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;


@Slf4j
public class WordToPdfUtil {
    public static File word2pdf(File wordFile) throws Exception {
        //输出文件
        File outputFile = new File(wordFile.getName().substring(0,wordFile.getName().lastIndexOf("."))+".pdf");
        //输入文件
        FileInputStream fileInputStream = new FileInputStream(wordFile);
        Document doc = new Document(fileInputStream);
        //存放地址
        try {
            doc.save(outputFile.getPath(),SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("word转pdf失败{}",wordFile.getName());
        }finally {
            fileInputStream.close();
        }
        return outputFile;
    }
}

实现

package com.ruifu.conversions.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fhzncloud.cloud.common.core.constant.SecurityConstants;
import com.fhzncloud.common.minio.service.MinioTemplate;
import com.ruifu.common.config.FileType;
import com.ruifu.common.constant.BizServiceNameConstants;
import com.ruifu.common.eneity.ConversionQueue;
import com.ruifu.common.feign.RemoteDocService;
import com.ruifu.common.feign.RemoteProjService;
import com.ruifu.common.feign.RemoteWorkSheetService;
import com.ruifu.common.utils.FileUtils;
import com.ruifu.common.utils.InputStream2byte;
import com.ruifu.conversions.service.FileConversionService;
import com.ruifu.conversions.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
@Slf4j
public class FileConversionServiceImpl implements FileConversionService {
    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private RemoteProjService remoteProjService;

    @Autowired
    private RemoteDocService remoteDocService;

    @Autowired
    private RemoteWorkSheetService remoteWorkSheetService;

    /**
     * 文件转换
     *
     * @param conversionQueue
     * @throws Exception
     */
    @Override
    public void conversionFileUpload(ConversionQueue conversionQueue){
        //判断消息对象是否为空
        if (null==conversionQueue) {
            log.error("mq消息为空");
            throw new RuntimeException("消息为空");
        }

        byte[] bytes = new byte[0];

        try {
            //输入流转字节数组
            InputStream inputStream = minioTemplate.getObject(conversionQueue.getVaultId(), conversionQueue.getPath());
            bytes= InputStream2byte.inputStream2byte(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取文件失败{}",conversionQueue.getSourceFileName());
        }
        //Byte数组转File
        File sourceFile = FileUtils.ByteToFile(bytes, conversionQueue.getSourceFileName());

        //获取文件后缀
        String extName = FilenameUtils.getExtension(sourceFile.getName());

        //判断源文件后缀是否为xls
        if (FileType.XLSX.equalsIgnoreCase(extName) || FileType.XLS.equalsIgnoreCase(extName)){
            getXlsToPdf(conversionQueue, bytes, sourceFile);
        }else if (FileType.DWG.equalsIgnoreCase(extName)){
            getDwgToPdf(conversionQueue, sourceFile);
        }else if (FileType.DOCX.equalsIgnoreCase(extName) || FileType.DOC.equalsIgnoreCase(extName)){
            getDocToPdf(conversionQueue, sourceFile);
        }else if (FileType.PPTX.equalsIgnoreCase(extName) || FileType.PPT.equalsIgnoreCase(extName)){
            getPptToPdf(conversionQueue, sourceFile);
        }

    }

    private void getPptToPdf(ConversionQueue conversionQueue, File sourceFile) {
        try {
            //ppt文件转换为pdf文件
            File pptFile = PptToPdfUtil.ppt2pdf(sourceFile);
            //上传附件
            uploadAttachment(sourceFile, pptFile,conversionQueue);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("office文件转换出错{}",sourceFile.getName());
        }
    }

    private void getDocToPdf(ConversionQueue conversionQueue, File sourceFile) {
        try {
            //doc文件转换为pdf文件
            File wordFile = WordToPdfUtil.word2pdf(sourceFile);
            //上传附件
            uploadAttachment(sourceFile, wordFile,conversionQueue);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("word文件转换出错{}",sourceFile.getName());
        }
    }

    private void getDwgToPdf(ConversionQueue conversionQueue, File sourceFile) {
        try {
            //dwg文件转换为pdf文件
            File dwgFile = DwgToPdfUtil.Dwg2Pdf(sourceFile);
            //上传附件
            uploadAttachment(sourceFile, dwgFile,conversionQueue);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("dwg文件转换出错{}",sourceFile.getName());
        }
    }

    private void getXlsToPdf(ConversionQueue conversionQueue, byte[] bytes, File sourceFile) {
        try {
            byte[] xlsByte = ExcelToPdfUtil.excel2pdf(bytes);
            //文件名前缀+"."
            String fileNamePrefix = conversionQueue.getSourceFileName().substring(0, conversionQueue.getSourceFileName().lastIndexOf(".")+1);
            File xlsToFile = FileUtils.ByteToFile(xlsByte, fileNamePrefix+ FileType.PDF);
            //上传附件
           uploadAttachment(sourceFile, xlsToFile,conversionQueue);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("xsl文件转换出错{}",sourceFile.getName());
        }
    }

    /**
     * 附件上传
     * @param sourceFile 源文件
     * @param annexFile  附件
     * @param conversionQueue 消息对象
     */
    private void uploadAttachment(File sourceFile, File annexFile,ConversionQueue conversionQueue) {
        if (annexFile.exists()) {
            log.info("文件转换完成{}",annexFile.getName());
            //删除源文件
            if (sourceFile.exists()) {
                if (sourceFile.delete()){
                    log.info("源文件删除成功{}",sourceFile.getName());
                }
            }else {
                log.info("源文件删除失败{}",sourceFile.getName());
            }
        }
        FileInputStream fileInputStream = null;
        try {
            //将pdf文件转换成InputStream输入流
            fileInputStream = new FileInputStream(annexFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        log.info("文件{}大小为:{}",annexFile.getName(),annexFile.length());

        try {
            String extName = FileUtil.extName(annexFile.getName());
            String path = IdUtil.simpleUUID() + StrUtil.DOT + extName;
            //上传
            minioTemplate.putObject(conversionQueue.getVaultId(), path, fileInputStream,
                    annexFile.length(),FileContentTypeUtils.contentType("."+extName));
            log.info("附件上传成功{}",annexFile.getName());
            //上传成功远程写入
            try {
                getServiceRemote(conversionQueue.getServiceName(),conversionQueue.getSourceFileId(),annexFile.length(),annexFile.getName(),path);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("远程调用附件初始化失败{}",annexFile.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转换文件上传失败{}",annexFile.getName());
        }
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("fileInputStream关闭失败");
        }finally {
            if (annexFile.delete()){
                log.info("临时文件删除成功{}",annexFile.getName());
            }
        }

    }

    /**
     * 更新附件到数据库
     * @param serviceName
     * @param sourceFileId
     * @param fileSize
     * @param newFileName
     * @param path
     */
    public void getServiceRemote(String serviceName,Long sourceFileId,Long fileSize,String newFileName,String path) {
        switch (serviceName){
            case BizServiceNameConstants.PROJECT_SERVICE:
                remoteProjService.initializationFileInfo(sourceFileId, fileSize, newFileName, path, SecurityConstants.FROM_IN);
                //远程调用项目任务服务
                break;
            case BizServiceNameConstants.DOC_SERVICE:
                //远程调用文档服务
                remoteDocService.initializationFileInfo(sourceFileId, fileSize, newFileName, path, SecurityConstants.FROM_IN);
                break;
            case BizServiceNameConstants.WORKSHEET_SERVICE:
                //远程调用变更服务
                break;
            default:break;
        }
    }
}

总结

优点:比openoffice好一点,不需要再去安装openoffice服务以及远程连接openoffice了,
效果的话xls能分页展示展示多个sheet比openoffice的A4裁切好上不少.
缺点:优点吃内存,需要调整jvm内存分配,其次就是有水印(虽然可以去掉)