shichongfu
2023-06-12 c6d5a3e6711e58546254333aa1184360a841c6bb
文档合并、转换
已修改3个文件
191 ■■■■ 文件已修改
src/main/java/com/product/file/config/FileCode.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/service/FileManagerService.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/util/AsposeUtil.java 185 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/config/FileCode.java
@@ -74,6 +74,10 @@
    GET_CLIENT_INFO_FAIL("获取客户信息失败", ModuleEnum.FILE.getValue() + "052"),
    RE_TRANSFER_FILE_WAIT_FAIL("再次转换pdf文件等待异常", ModuleEnum.FILE.getValue() + "053"),
    DOC_CONVERT_FALL("文档转换失败", ModuleEnum.FILE.getValue() + "054"),
    DOC_MERGE_FALL("文档合同并失败", ModuleEnum.FILE.getValue() + "055"),
    DOC_CONVERT_FILE_NOT_EXIST_FALL("文档转换失败,文件不存在", ModuleEnum.FILE.getValue() + "056"),
    DOC_CONVERT_NOT_SUPPORT_FILE_FALL("文档转换失败,不支持的文档类型", ModuleEnum.FILE.getValue() + "057"),
    ;
src/main/java/com/product/file/service/FileManagerService.java
@@ -30,9 +30,7 @@
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
 * Copyright  LX-BASE
src/main/java/com/product/file/util/AsposeUtil.java
@@ -8,12 +8,18 @@
import java.math.RoundingMode;
import java.text.DecimalFormat;
import com.aspose.cells.Cells;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
import com.aspose.cells.WorksheetCollection;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.SaveFormat;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.file.config.FileCode;
public class AsposeUtil {
    //是否初始了license
@@ -45,7 +51,7 @@
            isInitLicense=true;
        } catch (Exception e) {
            result=false;
            throw new BaseException(e);
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(is!=null) {
                try {
@@ -75,14 +81,13 @@
                file.mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            File pdfFile = new File(OutPutPath);// 输出路径
            fileOS = new FileOutputStream(pdfFile);
            fileOS = new FileOutputStream(OutPutPath);
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);
        } catch (Exception e) {
            throw new BaseException(e);
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
@@ -93,6 +98,58 @@
                }
            }
        }
    }
    public static void Excel2Html(String officePath,String OutPutPath)throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        FileOutputStream fileOS=null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            WorksheetCollection sheets=wb.getWorksheets();
            System.out.println("sheet个数:"+sheets.getCount());
            for(int i=0;i<sheets.getCount();i++) {
                setAutoWithHeight(sheets.get(i));
            }
            fileOS = new FileOutputStream(OutPutPath);
            wb.save(fileOS, SaveFormat.HTML);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }catch(IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * 设置单元格的自动适宽、高
     * @param sheet
     * @throws Exception
     */
    public static void setAutoWithHeight(Worksheet sheet)throws Exception
    {
        Cells cells =sheet.getCells();
        int columnCount = cells.getMaxColumn();  //获取表页的最大列数
        int rowCount = cells.getMaxRow();        //获取表页的最大行数
        if(columnCount<0 ||rowCount<0 )return ;
        for (int col = 0; col < columnCount; col++)
        {
            sheet.autoFitColumn(col, 0, rowCount);
        }
        for (int row = 0; row < rowCount; row++)
        {
            sheet.autoFitRow(row, 0, columnCount);
        }
    }
    /**
     * 
@@ -108,15 +165,14 @@
        FileOutputStream fileOS=null;
        try {
            File file = new File(OutPutPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            if (!file.exists()) {
                file.mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            File pdfFile = new File(OutPutPath);// 输出路径
            fileOS = new FileOutputStream(pdfFile);
            fileOS = new FileOutputStream(OutPutPath);
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            throw new BaseException(e);
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
@@ -145,15 +201,12 @@
            if (!PathFile.exists()) {
                PathFile.mkdirs();
            }
            InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径
            InputStream slides = new FileInputStream(officePath);// 原始ppt路径
            Presentation pres = new Presentation(slides);
            File file = new File(OutPutPath);// 输出pdf路径
            fileOS = new FileOutputStream(file);
            fileOS = new FileOutputStream(OutPutPath);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
            fileOS.flush();
            fileOS.close();
        } catch (Exception e) {
            throw new BaseException(e);
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
@@ -175,33 +228,24 @@
    public static String OfficeToPdf(String officePath,String outFile,String officeType )throws BaseException {
        SpringMVCContextHolder.getSystemLogger().info("The file of office type:"+officePath);
        SpringMVCContextHolder.getSystemLogger().info("The file of PDF type:"+outFile);
        if("pdf".equals(officeType)) {
            return outFile;
        }
        File file = new File(officePath);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if (file.exists()&& !"pdf".equals(officeType)) {
            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
//            if(Size>10){
            SpringMVCContextHolder.getSystemLogger().info("The file size:"+Size+"MB");
//            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            if(officeType.equals("doc")||officeType.equals("docx")){
        if (file.exists()) {
            if(officeType.equals("doc")||officeType.equals("docx")){
                Word2Pdf(officePath,outFile);
            }else if(officeType.equals("xls")||officeType.equals("xlsx")){
                Excel2Pdf(officePath,outFile);
//                Excel2Pdf(officePath,outFile);
                Excel2Html(officePath,outFile);
            }else if(officeType.equals("ppt")||officeType.equals("pptx")){
                PPT2Pdf(officePath,outFile);
            }else{
                SpringMVCContextHolder.getSystemLogger().info("File types that cannot be converted:"+officeType);
                throw new BaseException(FileCode.DOC_CONVERT_NOT_SUPPORT_FILE_FALL);
            }
        } else {
            SpringMVCContextHolder.getSystemLogger().info("File Not Exist");
            throw new BaseException(FileCode.DOC_CONVERT_FILE_NOT_EXIST_FALL);
        }
        return outFile;
    }
@@ -212,7 +256,6 @@
     */
    public static String OfficeToPdf(String officePath) {
        //G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docx
        String[] split = officePath.split("⌒");
        int lastIndex = split[0].lastIndexOf(".");
        int lastNameIndex = split[0].lastIndexOf("/");
@@ -261,7 +304,79 @@
        }
        return OutPutPath+officeName;
    }
    /**
     * word文档的合并
     * @param targetWordFile
     * @param sourceWordFile
     * @return
     * @throws Exception
     */
    public static File mergeWord(String targetWordFile,String sourceWordFile ) throws BaseException{
        File target=new File(targetWordFile);
        File source=new File(sourceWordFile);
        return mergeWord(target,source);
    }
    /**
     * word文档的合并
     * @param targetWordFile
     * @param sourceWordFile
     * @return
     * @throws Exception
     */
    public static File mergeWord(File target,File source ) throws BaseException{
        if(!target.exists() && !source.exists()) {
            return null;
        }else if(!source.exists() && target.exists()) {
            return target;
        }else if(source.exists() && !target.exists()) {
            return source;
        }
        // 验证License
        if (!getLicense(2)) {
            return null;
        }
        FileInputStream tin=null;
        FileInputStream sin=null;
        FileOutputStream out=null;
        String temp=target.getParent()+File.separator+"mergeTemp";
        File temp_target=new File(temp+File.separator+target.getName());
        try {
            tin=new FileInputStream(target);
            sin=new FileInputStream(source);
            Document targetDoc = new Document(tin);
            Document sourceDoc = new Document(sin);
            targetDoc.appendDocument(sourceDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
            File dir=new File(temp);
            if(!dir.exists()) {
                if(dir.mkdirs()) {
                    if(temp_target.createNewFile()) {
                        out=new FileOutputStream(temp_target);
                        targetDoc.save(out, SaveFormat.DOCX);
                    }
                }
            }
        }catch(Exception e) {
            throw new BaseException(FileCode.DOC_MERGE_FALL,e);
        }
        finally{
            try {
                if(tin!=null) {
                    tin.close();
                }
                if(sin!=null) {
                    sin.close();
                }
                if(out!=null) {
                    out.flush();
                    out.close();
                }
            }catch(IOException e) {
                throw new BaseException(FileCode.DOC_MERGE_FALL,e);
            }
        }
        return temp_target;
    }
    public static void main(String args[]) {
        String file="E:/work/沄崃/FE6.6产品报价工具-新 - 副本.xlsx";
        AsposeUtil.OfficeToPdf(file);