From a7e5e29bd9771b9cc65cfe09d213c470bbe4166b Mon Sep 17 00:00:00 2001
From: 许鹏程 <1821349743@qq.com>
Date: 星期三, 17 七月 2024 18:28:11 +0800
Subject: [PATCH] 添加pom版本号

---
 src/main/java/com/product/file/service/OnlineDocumentEditService.java |   13 
 src/main/java/com/product/file/util/AsposeUtil.java                   |  870 +++++++++++++++++++++++++++--------------------------
 src/main/java/com/product/file/util/FileUtil.java                     |   56 ++
 src/main/java/com/product/file/service/MergeDoc.java                  |   19 
 4 files changed, 509 insertions(+), 449 deletions(-)

diff --git a/src/main/java/com/product/file/service/MergeDoc.java b/src/main/java/com/product/file/service/MergeDoc.java
index 58343ea..cf29496 100644
--- a/src/main/java/com/product/file/service/MergeDoc.java
+++ b/src/main/java/com/product/file/service/MergeDoc.java
@@ -1,16 +1,10 @@
 package com.product.file.service;
 
 import cn.hutool.core.io.FileUtil;
-import com.product.file.util.AsposeUtil;
-import com.product.file.util.FileUtils;
-import org.apache.poi.openxml4j.opc.OPCPackage;
-import org.apache.poi.xwpf.usermodel.XWPFDocument;
-import org.apache.tomcat.util.http.fileupload.IOUtils;
 import org.apache.xmlbeans.XmlOptions;
 import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
 
 import java.io.*;
-import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -24,16 +18,19 @@
 	 * @param srcDocxs 闇�瑕佸悎骞剁殑鐩爣docx鏂囦欢
 	 * @param response 鍚堝苟鍚庣殑docx杈撳嚭鏂囦欢
 	 */
-	public static File mergeDoc(List<File> srcDocxs, String tempFilePath) {
+	public static File mergeDoc(List<File> srcDocxs, String tempFilePath) throws Exception {
+		File file = null;
 		if (srcDocxs.size() > 1) {
-			File file = srcDocxs.get(0);
+			file = srcDocxs.get(0);
 			for (int i = 1; i < srcDocxs.size(); i++) {
-				file = AsposeUtil.mergeWord(file, srcDocxs.get(i));
+				file = com.product.file.util.FileUtil.mergeFile(file, srcDocxs.get(i));
 			}
-			FileUtil.copyFile(file, new File(tempFilePath));
+			File file1 = new File(tempFilePath);
+			FileUtil.copyFile(file, file1);
 			FileUtil.del(file);
+			return file1;
 		}
-		return null;
+		return file;
 	}
 
 	/**
diff --git a/src/main/java/com/product/file/service/OnlineDocumentEditService.java b/src/main/java/com/product/file/service/OnlineDocumentEditService.java
index 819baea..8f39bf7 100644
--- a/src/main/java/com/product/file/service/OnlineDocumentEditService.java
+++ b/src/main/java/com/product/file/service/OnlineDocumentEditService.java
@@ -75,7 +75,15 @@
 			}
 			List<File> fileList = new ArrayList<>(3);
 			if (!StringUtils.isEmpty(document_template)) {
-				fileList.add(fileManagerService.getFile(document_template));
+				File file1 = fileManagerService.getFile(document_template);
+				//鍒ゆ柇file1鐨勬枃浠剁被鍨�
+				if (file1.getName().substring(file1.getName().lastIndexOf(".") + 1).equals("doc")) {
+					//杞崲涓篸ocx
+					File docx = com.product.file.util.FileUtil.toDocx(file1);
+					FileUtil.del(file1);
+					file1 = docx;
+				}
+				fileList.add(file1);
 				fileList.add(file);
 			} else {
 				fileList.add(file);
@@ -86,7 +94,7 @@
 			File mergeFile = MergeDoc.mergeDoc(fileList, Global.getSystemConfig("upload.file.temp.path", "./attachment/temp") +
 					File.separator + "nest_red_document_" + IdUtil.randomUUID() + "_" + ff.getString("file_uuid"));
 			if (mergeFile != null && mergeFile.isFile()) {
-				if("doc".equals(fileType)){
+				if ("doc".equals(fileType)) {
 					//灏哾ocx鏂囦欢杞崲涓篸oc鏂囦欢
 					File f = mergeFile;
 					mergeFile = com.product.file.util.FileUtil.toDoc(f);
@@ -104,6 +112,7 @@
 		} catch (BaseException e) {
 			throw e;
 		} catch (Exception e) {
+			e.printStackTrace();
 			throw new BaseException(FileCode.NEST_RED_DOCUMENT_FAIL);
 		}
 	}
diff --git a/src/main/java/com/product/file/util/AsposeUtil.java b/src/main/java/com/product/file/util/AsposeUtil.java
index d584bae..25e6f39 100644
--- a/src/main/java/com/product/file/util/AsposeUtil.java
+++ b/src/main/java/com/product/file/util/AsposeUtil.java
@@ -21,457 +21,472 @@
 import com.product.file.config.FileCode;
 
 public class AsposeUtil {
-    private static int OFFICE_XLS=1;
-    private static int OFFICE_WORD=2;
-    private static int OFFICE_PPT=3;
-    private static boolean OFFICE_XLS_=false;
-    private static boolean OFFICE_WORD_=false;
-    private static boolean OFFICE_PPT_=false;
+	private static int OFFICE_XLS = 1;
+	private static int OFFICE_WORD = 2;
+	private static int OFFICE_PPT = 3;
+	private static boolean OFFICE_XLS_ = false;
+	private static boolean OFFICE_WORD_ = false;
+	private static boolean OFFICE_PPT_ = false;
 	//鏄惁鍒濆浜唋icense
-	private static boolean isInitLicense=false;
-    /**
-     * 鑾峰彇license
-     * @return
-     */
-    public static boolean getLicense(int type)throws BaseException {
-    	//宸茬粡鍒濆杩囷紝涓嶅啀鍒濆
-    	if(isInitLicense) {
-    		return true;
-    	}
-        boolean result = true;
-        InputStream is = null;
-        try {
-        	if(type==OFFICE_XLS && !OFFICE_XLS_ ) {
-                is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
-                com.aspose.cells.License excel = new com.aspose.cells.License();
-                excel.setLicense(is);
-                OFFICE_XLS_=true;
-            }else if(type==OFFICE_WORD && !OFFICE_WORD_ ){
-                is =  AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
-                com.aspose.words.License word = new com.aspose.words.License();
-                word.setLicense(is);
-                OFFICE_WORD_=true;
-            }else if(type==OFFICE_PPT && ! OFFICE_PPT_) {
-                is =  AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
-                com.aspose.slides.License ppt = new com.aspose.slides.License();
-                ppt.setLicense(is);
-                OFFICE_PPT_=true;
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        	result=false;
-        	throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
-        }finally{
-			if(is!=null) {
+	private static boolean isInitLicense = false;
+
+	/**
+	 * 鑾峰彇license
+	 *
+	 * @return
+	 */
+	public static boolean getLicense(int type) throws BaseException {
+		//宸茬粡鍒濆杩囷紝涓嶅啀鍒濆
+		if (isInitLicense) {
+			return true;
+		}
+		boolean result = true;
+		InputStream is = null;
+		try {
+			if (type == OFFICE_XLS && !OFFICE_XLS_) {
+				is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
+				com.aspose.cells.License excel = new com.aspose.cells.License();
+				excel.setLicense(is);
+				OFFICE_XLS_ = true;
+			} else if (type == OFFICE_WORD && !OFFICE_WORD_) {
+				//鍒ゆ柇鏍硅矾寰勬槸鍚︿负web妯″潡
+
+				is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
+				com.aspose.words.License word = new com.aspose.words.License();
+				word.setLicense(is);
+				OFFICE_WORD_ = true;
+			} else if (type == OFFICE_PPT && !OFFICE_PPT_) {
+				is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
+				com.aspose.slides.License ppt = new com.aspose.slides.License();
+				ppt.setLicense(is);
+				OFFICE_PPT_ = true;
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+			result = false;
+			throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
+		} finally {
+			if (is != null) {
 				try {
 					is.close();
-				}catch(IOException e) {
+				} catch (IOException e) {
 					throw new BaseException(e);
 				}
 			}
 		}
-        return result;
-    }
-    /**
-     *
-     * @param officePath
-     * @param OutPutPath
-     * @throws BaseException
-     */
-    public static void Excel2Pdf(String officePath,String OutPutPath)throws BaseException {
-        // 楠岃瘉License
-        if (!getLicense(1)) {
-            return;
-        }
-        FileOutputStream fileOS=null;
-        try {
-            File file = new File(OutPutPath);
-            if (!file.getParentFile().exists()) {
-                file.getParentFile().mkdirs();
-            }
-            Workbook wb = new Workbook(officePath);// 鍘熷excel璺緞
-            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(FileCode.DOC_CONVERT_FALL,e);
-        }finally{
-			if(fileOS!=null) {
+		return result;
+	}
+
+	/**
+	 * @param officePath
+	 * @param OutPutPath
+	 * @throws BaseException
+	 */
+	public static void Excel2Pdf(String officePath, String OutPutPath) throws BaseException {
+		// 楠岃瘉License
+		if (!getLicense(1)) {
+			return;
+		}
+		FileOutputStream fileOS = null;
+		try {
+			File file = new File(OutPutPath);
+			if (!file.getParentFile().exists()) {
+				file.getParentFile().mkdirs();
+			}
+			Workbook wb = new Workbook(officePath);// 鍘熷excel璺緞
+			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(FileCode.DOC_CONVERT_FALL, e);
+		} finally {
+			if (fileOS != null) {
 				try {
 					fileOS.flush();
 					fileOS.close();
-				}catch(IOException e) {
+				} catch (IOException e) {
 					throw new BaseException(e);
 				}
 			}
 		}
-    }
-    /**
-     *
-     * @param officePath
-     * @param OutPutPath
-     * @throws BaseException
-     */
-    public static void xls2xlsx(String officePath,String OutPutPath,String officeType)throws BaseException {
-        // 楠岃瘉License
-        if (!getLicense(1)) {
-            return;
-        }
-        if("xlsx".equals(officeType)) {
-        	FileUtil.copyFile(new File(officePath), OutPutPath);
-        	return ;
-        }
-        FileOutputStream fileOS=null;
-        try {
-            File file = new File(OutPutPath);
-            if (!file.getParentFile().exists()) {
-                file.getParentFile().mkdirs();
-            }
-            Workbook wb = new Workbook(officePath);// 鍘熷excel璺緞
-            fileOS = new FileOutputStream(OutPutPath);
-            wb.save(fileOS, com.aspose.cells.SaveFormat.XLSX);
-        } catch (Exception e) {
-        	throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
-        }finally{
-			if(fileOS!=null) {
+	}
+
+	/**
+	 * @param officePath
+	 * @param OutPutPath
+	 * @throws BaseException
+	 */
+	public static void xls2xlsx(String officePath, String OutPutPath, String officeType) throws BaseException {
+		// 楠岃瘉License
+		if (!getLicense(1)) {
+			return;
+		}
+		if ("xlsx".equals(officeType)) {
+			FileUtil.copyFile(new File(officePath), OutPutPath);
+			return;
+		}
+		FileOutputStream fileOS = null;
+		try {
+			File file = new File(OutPutPath);
+			if (!file.getParentFile().exists()) {
+				file.getParentFile().mkdirs();
+			}
+			Workbook wb = new Workbook(officePath);// 鍘熷excel璺緞
+			fileOS = new FileOutputStream(OutPutPath);
+			wb.save(fileOS, com.aspose.cells.SaveFormat.XLSX);
+		} catch (Exception e) {
+			throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
+		} finally {
+			if (fileOS != null) {
 				try {
 					fileOS.flush();
 					fileOS.close();
-				}catch(IOException e) {
+				} catch (IOException e) {
 					throw new BaseException(e);
 				}
 			}
 		}
-    }
-    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.getParentFile().exists()) {
-                file.getParentFile().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));
-            }
+	}
+
+	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.getParentFile().exists()) {
+				file.getParentFile().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));
+			}
 //            HtmlSaveOptions options = new HtmlSaveOptions();
 //            options.setPresentationPreference(true);
-            fileOS = new FileOutputStream(OutPutPath);
-            wb.save(fileOS, com.aspose.cells.SaveFormat.HTML);
-        } catch (Exception e) {
-        	throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
-        }finally{
-			if(fileOS!=null) {
+			fileOS = new FileOutputStream(OutPutPath);
+			wb.save(fileOS, com.aspose.cells.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) {
+				} 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);
-        }
-    }
-    /**
-     *
-     * @param officePath
-     * @param OutPutPath
-     * @throws BaseException
-     */
-    public static void Word2Pdf(String officePath,String OutPutPath) throws BaseException {
-        // 楠岃瘉License
-        if (!getLicense(2)) {
-            return;
-        }
-        FileOutputStream fileOS=null;
-        try {
-            File file = new File(OutPutPath);
-            if (!file.getParentFile().exists()) {
-                file.getParentFile().mkdirs();
-            }
-            Document doc = new Document(officePath);// 鍘熷word璺緞
-            fileOS = new FileOutputStream(OutPutPath);
+	}
+
+	/**
+	 * 璁剧疆鍗曞厓鏍肩殑鑷姩閫傚銆侀珮
+	 *
+	 * @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);
+		}
+	}
+
+	/**
+	 * @param officePath
+	 * @param OutPutPath
+	 * @throws BaseException
+	 */
+	public static void Word2Pdf(String officePath, String OutPutPath) throws BaseException {
+		// 楠岃瘉License
+		if (!getLicense(2)) {
+			return;
+		}
+		FileOutputStream fileOS = null;
+		try {
+			File file = new File(OutPutPath);
+			if (!file.getParentFile().exists()) {
+				file.getParentFile().mkdirs();
+			}
+			Document doc = new Document(officePath);// 鍘熷word璺緞
+			fileOS = new FileOutputStream(OutPutPath);
 			//涓嶄繚鐣欎慨璁㈢棔杩�
 			doc.acceptAllRevisions();
-            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
-        } catch (Exception e) {
-        	throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
-        }finally{
-			if(fileOS!=null) {
+			doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
+		} catch (Exception e) {
+			throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
+		} finally {
+			if (fileOS != null) {
 				try {
 					fileOS.flush();
 					fileOS.close();
-				}catch(IOException e) {
+				} catch (IOException e) {
 					throw new BaseException(e);
 				}
 			}
 		}
-    }
-    /**
-     *
-     * @param officePath
-     * @param OutPutPath
-     * @throws BaseException
-     */
-    public static void PPT2Pdf(String officePath,String OutPutPath)throws BaseException {
-        // 楠岃瘉License
-        if (!getLicense(3)) {
-            return;
-        }
-        FileOutputStream fileOS=null;
-        try {
-            File PathFile = new File(OutPutPath);
-            if (!PathFile.getParentFile().exists()) {
-                PathFile.getParentFile().mkdirs();
-            }
-            InputStream slides = new FileInputStream(officePath);// 鍘熷ppt璺緞
-            Presentation pres = new Presentation(slides);
-            fileOS = new FileOutputStream(OutPutPath);
-            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
-        } catch (Exception e) {
-        	throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
-        }finally{
-			if(fileOS!=null) {
+	}
+
+	/**
+	 * @param officePath
+	 * @param OutPutPath
+	 * @throws BaseException
+	 */
+	public static void PPT2Pdf(String officePath, String OutPutPath) throws BaseException {
+		// 楠岃瘉License
+		if (!getLicense(3)) {
+			return;
+		}
+		FileOutputStream fileOS = null;
+		try {
+			File PathFile = new File(OutPutPath);
+			if (!PathFile.getParentFile().exists()) {
+				PathFile.getParentFile().mkdirs();
+			}
+			InputStream slides = new FileInputStream(officePath);// 鍘熷ppt璺緞
+			Presentation pres = new Presentation(slides);
+			fileOS = new FileOutputStream(OutPutPath);
+			pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
+		} catch (Exception e) {
+			throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
+		} finally {
+			if (fileOS != null) {
 				try {
 					fileOS.flush();
 					fileOS.close();
-				}catch(IOException e) {
+				} catch (IOException e) {
 					throw new BaseException(e);
 				}
 			}
 		}
-    }
-    /**
-     * 鏂囨。杞崲
-     * @param officePath
-     * @param outFile
-     * @return
-     * @throws BaseException
-     */
-    public static String OfficeToPdf(String officePath,String outFile,String officeType )throws BaseException {
-    	officeType=officeType.toLowerCase();
-        SpringMVCContextHolder.getSystemLogger().info("The file of office type:"+officePath);
-        if("pdf".equals(officeType)) {
-        	return outFile;
-        }
-        File file = new File(officePath);
-        //鍒ゆ柇褰撳墠office鏂囦欢鏄惁宸茬粡杞负PDF,濡傛灉宸茶浆涓篜DF灏变笉闇�瑕佸啀娆¤浆鎹€��
-        if (file.exists()) {
-        	if(officeType.equals("doc")||officeType.equals("docx")){
-                Word2Pdf(officePath,outFile);
-            }else if(officeType.equals("xls")||officeType.equals("xlsx")){
+	}
+
+	/**
+	 * 鏂囨。杞崲
+	 *
+	 * @param officePath
+	 * @param outFile
+	 * @return
+	 * @throws BaseException
+	 */
+	public static String OfficeToPdf(String officePath, String outFile, String officeType) throws BaseException {
+		officeType = officeType.toLowerCase();
+		SpringMVCContextHolder.getSystemLogger().info("The file of office type:" + officePath);
+		if ("pdf".equals(officeType)) {
+			return outFile;
+		}
+		File file = new File(officePath);
+		//鍒ゆ柇褰撳墠office鏂囦欢鏄惁宸茬粡杞负PDF,濡傛灉宸茶浆涓篜DF灏变笉闇�瑕佸啀娆¤浆鎹€��
+		if (file.exists()) {
+			if (officeType.equals("doc") || officeType.equals("docx")) {
+				Word2Pdf(officePath, outFile);
+			} else if (officeType.equals("xls") || officeType.equals("xlsx")) {
 //                Excel2Pdf(officePath,outFile);
-                Excel2Html(officePath,outFile);
+				Excel2Html(officePath, outFile);
 //                xls2xlsx(officePath,outFile,officeType);
-            }else if(officeType.equals("ppt")||officeType.equals("pptx")){
-                PPT2Pdf(officePath,outFile);
-            }else{
-            	throw new BaseException(FileCode.DOC_CONVERT_NOT_SUPPORT_FILE_FALL);
-            }
-        } else {
-        	throw new BaseException(FileCode.DOC_CONVERT_FILE_NOT_EXIST_FALL);
-        }
-        return outFile;
-    }
-    /**
-     * 鏂囨。杞崲
-     * @param officePath
-     * @return
-     */
-    public static String OfficeToPdf(String officePath) {
+			} else if (officeType.equals("ppt") || officeType.equals("pptx")) {
+				PPT2Pdf(officePath, outFile);
+			} else {
+				throw new BaseException(FileCode.DOC_CONVERT_NOT_SUPPORT_FILE_FALL);
+			}
+		} else {
+			throw new BaseException(FileCode.DOC_CONVERT_FILE_NOT_EXIST_FALL);
+		}
+		return outFile;
+	}
 
-        String[] split = officePath.split("鈱�");
-        int lastIndex = split[0].lastIndexOf(".");
-        int lastNameIndex = split[0].lastIndexOf("/");
+	/**
+	 * 鏂囨。杞崲
+	 *
+	 * @param officePath
+	 * @return
+	 */
+	public static String OfficeToPdf(String officePath) {
 
-        String officeType = split[0].substring(lastIndex+1);
-        String officeName = split[0].substring(lastNameIndex+1,lastIndex);
-        String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";
-        System.out.println("杈撳嚭鐩綍锛�"+OutPutPath);
-        File file = new File(split[0]);
-        //鍒ゆ柇褰撳墠office鏂囦欢鏄惁宸茬粡杞负PDF,濡傛灉宸茶浆涓篜DF灏变笉闇�瑕佸啀娆¤浆鎹€��
-        if (file.exists()) {
-            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
-            try {
-                if(officeType.equals("doc")||officeType.equals("docx")){
-                    Word2Pdf(split[0],OutPutPath+"/"+officeName+".pdf");
-                }else if(officeType.equals("xls")||officeType.equals("xlsx")){
+		String[] split = officePath.split("鈱�");
+		int lastIndex = split[0].lastIndexOf(".");
+		int lastNameIndex = split[0].lastIndexOf("/");
+
+		String officeType = split[0].substring(lastIndex + 1);
+		String officeName = split[0].substring(lastNameIndex + 1, lastIndex);
+		String OutPutPath = split[0].substring(0, lastNameIndex + 1) + "office/";
+		System.out.println("杈撳嚭鐩綍锛�" + OutPutPath);
+		File file = new File(split[0]);
+		//鍒ゆ柇褰撳墠office鏂囦欢鏄惁宸茬粡杞负PDF,濡傛灉宸茶浆涓篜DF灏变笉闇�瑕佸啀娆¤浆鎹€��
+		if (file.exists()) {
+			//"doc", "docx", "xls","xlsx", "ppt", "pptx"
+			try {
+				if (officeType.equals("doc") || officeType.equals("docx")) {
+					Word2Pdf(split[0], OutPutPath + "/" + officeName + ".pdf");
+				} else if (officeType.equals("xls") || officeType.equals("xlsx")) {
 //                	Excel2Html(split[0],OutPutPath+"/"+officeName+".html");
-                	xls2xlsx(split[0],OutPutPath+"/"+officeName+".xlsx",officeType);
-                }else if(officeType.equals("ppt")||officeType.equals("pptx")){
-                    PPT2Pdf(split[0],OutPutPath+"/"+officeName+".pdf");
-                }else{
-                    System.out.println("鏃犳硶璇嗗埆璇ユ枃浠讹紒");
-                    return "Error";
-                }
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        } else {
-            return "NotExists";
-        }
-        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
-     * @param
-     * @return
-     * @throws Exception
-     */
-    public static File mergeWord(File target,File source ) throws BaseException{
+					xls2xlsx(split[0], OutPutPath + "/" + officeName + ".xlsx", officeType);
+				} else if (officeType.equals("ppt") || officeType.equals("pptx")) {
+					PPT2Pdf(split[0], OutPutPath + "/" + officeName + ".pdf");
+				} else {
+					System.out.println("鏃犳硶璇嗗埆璇ユ枃浠讹紒");
+					return "Error";
+				}
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		} else {
+			return "NotExists";
+		}
+		return OutPutPath + officeName;
+	}
 
-    	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(OFFICE_WORD)) {
-            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);
-//	    	docBlankProcess(targetDoc);
-	    	targetDoc.appendDocument(sourceDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
+	/**
+	 * 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
+	 * @param
+	 * @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(OFFICE_WORD)) {
+			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);
+			docBlankProcess(targetDoc);
+			targetDoc.appendDocument(sourceDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
 //	    	NodeCollection t =sourceDoc.getChildNodes();
-//	    	for(int c=0;c<t.getCount();c++) {
-//	    		targetDoc.getChildNodes().add(t.get(c));
-//	    	}
-	    	File dir=new File(temp);
-	    	if(!dir.exists()) {
-	    		dir.mkdirs();
-	    	}
-	    	if(temp_target.exists()) {
-	    		temp_target.delete();
-	    	}
-	    	if(temp_target.createNewFile()) {
-				out=new FileOutputStream(temp_target);
+//			for (int c = 0; c < t.getCount(); c++) {
+//				targetDoc.getChildNodes().add(t.get(c));
+//			}
+			File dir = new File(temp);
+			if (!dir.exists()) {
+				dir.mkdirs();
+			}
+			if (temp_target.exists()) {
+				temp_target.delete();
+			}
+			if (temp_target.createNewFile()) {
+				out = new FileOutputStream(temp_target);
 				targetDoc.save(out, SaveFormat.DOCX);
 			}
-    	}catch(Exception e) {
-    		e.printStackTrace();
-    		throw new BaseException(FileCode.DOC_MERGE_FALL,e);
-    	}
-    	finally{
-    		try {
-	    		if(tin!=null) {
+		} catch (Exception e) {
+			e.printStackTrace();
+			throw new BaseException(FileCode.DOC_MERGE_FALL, e);
+		} finally {
+			try {
+				if (tin != null) {
 					tin.close();
 				}
-	    		if(sin!=null) {
-	    			sin.close();
+				if (sin != null) {
+					sin.close();
 				}
-				if(out!=null) {
+				if (out != null) {
 					out.flush();
-	    			out.close();
+					out.close();
 				}
-    		}catch(IOException e) {
-				throw new BaseException(FileCode.DOC_MERGE_FALL,e);
+			} catch (IOException e) {
+				throw new BaseException(FileCode.DOC_MERGE_FALL, e);
 			}
 		}
-    	return temp_target;
-    }
+		return temp_target;
+	}
 
-    public static void docBlankProcess(Document targetDoc) {
-    	NodeCollection nodes=targetDoc.getChildNodes(NodeType.PARAGRAPH, true);
-    	System.out.println(nodes.getCount());
-    	List <Node> ss=new ArrayList<>();
-    	for(Paragraph para :(Iterable<Paragraph>) nodes) {
-    		System.out.println("===========================");
-    		System.out.println(para.isEndOfSection());
-    		System.out.println(para.hasChildNodes());
-    		String text=para.getText();
-    		if("\r".equals(text))System.out.println("\\\\r");
-    		else if("\f".equals(text))System.out.println("\\\\f");
-    		else if("".equals(text.trim())) System.out.println("绌烘牸");
-    		else System.out.println(text);
+	public static void docBlankProcess(Document targetDoc) {
+		NodeCollection nodes = targetDoc.getChildNodes(NodeType.PARAGRAPH, true);
+		System.out.println(nodes.getCount());
+		List<Node> ss = new ArrayList<>();
+		for (Paragraph para : (Iterable<Paragraph>) nodes) {
+			System.out.println("===========================");
+			System.out.println(para.isEndOfSection());
+			System.out.println(para.hasChildNodes());
+			String text = para.getText();
+			if ("\r".equals(text)) System.out.println("\\\\r");
+			else if ("\f".equals(text)) System.out.println("\\\\f");
+			else if ("".equals(text.trim())) System.out.println("绌烘牸");
+			else System.out.println(text);
 
-    		NodeCollection pnodes =para.getChildNodes();
-    		if(pnodes.getCount()==0)para.appendChild(new Run(targetDoc,"a"));
-    		if(para.isEndOfSection())para.appendChild(new Run(targetDoc,"B"));
-    		System.out.println("sub nodes:"+pnodes.getCount());
-    		for(int i=0;i<pnodes.getCount();i++) {
-    			Node d=pnodes.get(i);
-    			System.out.println("type:"+NodeType.getName(d.getNodeType()));
+			NodeCollection pnodes = para.getChildNodes();
+			if (pnodes.getCount() == 0) para.appendChild(new Run(targetDoc, "a"));
+			if (para.isEndOfSection()) para.appendChild(new Run(targetDoc, "B"));
+			System.out.println("sub nodes:" + pnodes.getCount());
+			for (int i = 0; i < pnodes.getCount(); i++) {
+				Node d = pnodes.get(i);
+				System.out.println("type:" + NodeType.getName(d.getNodeType()));
 
-    			if("\r".equals(text))System.out.println("\\\\r");
-        		else if("\f".equals(text))System.out.println("\\\\f");
-        		else if("".equals(text.trim())) System.out.println("绌烘牸");
-        		else System.out.println(text);
-    			if("BOOKMARK_END".equals(NodeType.getName(d.getNodeType()))) {
-    				BookmarkEnd b=(BookmarkEnd)d;
-    			}
-    			if(d.getNodeType()==NodeType.SHAPE) {
-    				ss.add(d);
-    			}
-    		}
+				if ("\r".equals(text)) System.out.println("\\\\r");
+				else if ("\f".equals(text)) System.out.println("\\\\f");
+				else if ("".equals(text.trim())) System.out.println("绌烘牸");
+				else System.out.println(text);
+				if ("BOOKMARK_END".equals(NodeType.getName(d.getNodeType()))) {
+					BookmarkEnd b = (BookmarkEnd) d;
+				}
+				if (d.getNodeType() == NodeType.SHAPE) {
+					ss.add(d);
+				}
+			}
 
 
-    	}
-    	for(Node d:ss) {
-    		d.remove();
-    	}
+		}
+		for (Node d : ss) {
+			d.remove();
+		}
 
-    }
+	}
 
-    private static String appendDoc(String sohuyepath, String xuyepath, boolean includeSection) throws Exception {
-        // 楠岃瘉License
-        if (!getLicense(OFFICE_WORD)) {
-            return null ;
-        }
-        Document dstDoc = new Document(sohuyepath);
-        Document srcDoc = new Document(xuyepath);
-        System.out.println("鐩爣鏂囨。椤垫暟锛�"+dstDoc.getPageCount()+" | 婧愭枃妗i〉鏁帮細"+srcDoc.getPageCount());
-        if (includeSection) {
+	public static File appendDoc(File source, File target) throws Exception {
+		return new File(appendDoc(source.getPath(), target.getPath(), false));
+	}
+
+	public static String appendDoc(String sohuyepath, String xuyepath, boolean includeSection) throws Exception {
+		// 楠岃瘉License
+		if (!getLicense(OFFICE_WORD)) {
+			return null;
+		}
+		Document dstDoc = new Document(sohuyepath);
+		Document srcDoc = new Document(xuyepath);
+		System.out.println("鐩爣鏂囨。椤垫暟锛�" + dstDoc.getPageCount() + " | 婧愭枃妗i〉鏁帮細" + srcDoc.getPageCount());
+		if (includeSection) {
 			Iterator<Section> var3 = srcDoc.getSections().iterator();
 			while (var3.hasNext()) {
 				Section srcSection = (Section) var3.next();
@@ -491,9 +506,9 @@
 
 			insertDocumentAfterNode(node, dstDoc, srcDoc);
 		}
-        File f=new File(sohuyepath);
-        dstDoc.save(f.getParent()+"/merge/"+f.getName());
-        return f.getParent()+"/merge/"+f.getName();
+		File f = new File(sohuyepath);
+		dstDoc.save(f.getParent() + "/merge/" + f.getName());
+		return f.getParent() + "/merge/" + f.getName();
 	}
 
 	private static void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc)
@@ -526,47 +541,48 @@
 		}
 	}
 
-    /**
-     * 鎶婃簮鏂囨。鍐呭鏀惧埌鏈�鍚庝竴椤电殑椤垫湯
-     * @param sohuyepath
-     * @return
-     * @throws Exception
-     */
-    private static void  appendDocToPageTail(String sohuyepath) throws Exception {
-        Document dstDoc = new Document(sohuyepath);
-        int destPages=dstDoc.getPageCount();
-        System.out.println("鍚堝苟鍚堢殑鏈�鍚庢�婚〉鏁帮細"+destPages);
-        Node lastNode=dstDoc.getLastSection().getBody().getLastChild();
-        Paragraph lp=null;
-        if(lastNode.getNodeType()==NodeType.PARAGRAPH){
-            lp=(Paragraph)lastNode;
-            Node ld=lp.getFirstChild();
-            while(ld!=null && ld.getNodeType()!=NodeType.SHAPE && ld.getNodeType()!=NodeType.RUN &&  ld.getNodeType()!=NodeType.TABLE){
-                System.out.println("type name "+NodeType.getName(ld.getNodeType()));
-                ld=ld.getPreviousSibling();
-            }
-        }
-        System.out.println("鏈�鍚庝竴鑺傜偣锛�"+NodeType.getName(lastNode.getNodeType()));
-        for(int i=0;i<40;i++) {
-            Run t = new Run(dstDoc, "======\r");
-            if(lp!=null){
-                lp.insertBefore(t,lp.getLastChild());
-                System.out.println("瀛愬厓绱犳暟锛�"+lp.getChildNodes().getCount());
-            }
-            System.out.println("鍚堝苟鍚堢殑鏈�鍚庢�婚〉鏁帮細"+dstDoc.getPageCount());
-            if(destPages < dstDoc.getPageCount()){
-                System.out.println("================鍒嗛〉=================");
-            }
-        }
-        File ff=new File(sohuyepath);
-        dstDoc.save(ff.getParent()+"/merge/"+ff.getName(),SaveFormat.DOCX);
-    }
+	/**
+	 * 鎶婃簮鏂囨。鍐呭鏀惧埌鏈�鍚庝竴椤电殑椤垫湯
+	 *
+	 * @param sohuyepath
+	 * @return
+	 * @throws Exception
+	 */
+	private static void appendDocToPageTail(String sohuyepath) throws Exception {
+		Document dstDoc = new Document(sohuyepath);
+		int destPages = dstDoc.getPageCount();
+		System.out.println("鍚堝苟鍚堢殑鏈�鍚庢�婚〉鏁帮細" + destPages);
+		Node lastNode = dstDoc.getLastSection().getBody().getLastChild();
+		Paragraph lp = null;
+		if (lastNode.getNodeType() == NodeType.PARAGRAPH) {
+			lp = (Paragraph) lastNode;
+			Node ld = lp.getFirstChild();
+			while (ld != null && ld.getNodeType() != NodeType.SHAPE && ld.getNodeType() != NodeType.RUN && ld.getNodeType() != NodeType.TABLE) {
+				System.out.println("type name " + NodeType.getName(ld.getNodeType()));
+				ld = ld.getPreviousSibling();
+			}
+		}
+		System.out.println("鏈�鍚庝竴鑺傜偣锛�" + NodeType.getName(lastNode.getNodeType()));
+		for (int i = 0; i < 40; i++) {
+			Run t = new Run(dstDoc, "======\r");
+			if (lp != null) {
+				lp.insertBefore(t, lp.getLastChild());
+				System.out.println("瀛愬厓绱犳暟锛�" + lp.getChildNodes().getCount());
+			}
+			System.out.println("鍚堝苟鍚堢殑鏈�鍚庢�婚〉鏁帮細" + dstDoc.getPageCount());
+			if (destPages < dstDoc.getPageCount()) {
+				System.out.println("================鍒嗛〉=================");
+			}
+		}
+		File ff = new File(sohuyepath);
+		dstDoc.save(ff.getParent() + "/merge/" + ff.getName(), SaveFormat.DOCX);
+	}
 
-    public static void main(String args[]) {
+	public static void main(String args[]) {
 //    	String file="E:/宸ヤ綔鍐呭.xlsx";
 //    	String file="E:/鐖嗙牬姣嶇嚎.xls";
 //    	String file="E:/閲囬泦鎻愬彇鏃ュ織琛ㄧ粨鏋�.xlsx";
-    	String file="E:/FE淇℃伅绯荤粺鍥戒骇鍖栬В鍐虫柟妗圴1.0.docx";
+		String file = "E:/FE淇℃伅绯荤粺鍥戒骇鍖栬В鍐虫柟妗圴1.0.docx";
 //    	AsposeUtil.OfficeToPdf(file);
 
 //    	AsposeUtil.mergeWord("E:\\QQ\\浣忔埧鎷呬繚缃崲鍏徃.docx","E:\\QQ\\浣忔埧鎷呬繚缃崲鍏徃2.docx");
@@ -575,17 +591,17 @@
 //    	}catch(Exception e) {
 //    		e.printStackTrace();
 //    	}
-    	try {
+		try {
 //			String sohuyepath="E:/QQ/浣忔埧鎷呬繚缃崲鍏徃.docx";
 //			String xuyepath="E:/QQ/FE淇℃伅绯荤粺鍥戒骇鍖栬В鍐虫柟妗圴1.0.docx";
 //			String npath=appendDoc(sohuyepath, xuyepath, false);
-			String tail="E:/QQ/浣忔埧鎷呬繚缃崲鍏徃2.docx";
+			String tail = "E:/QQ/浣忔埧鎷呬繚缃崲鍏徃2.docx";
 //            appendDoc(npath, tail, false);
-            appendDocToPageTail(tail);
+			appendDocToPageTail(tail);
 
 
-		}catch(Exception e) {
+		} catch (Exception e) {
 			e.printStackTrace();
 		}
-    }
+	}
 }
diff --git a/src/main/java/com/product/file/util/FileUtil.java b/src/main/java/com/product/file/util/FileUtil.java
index a7cdaa2..1b1e553 100644
--- a/src/main/java/com/product/file/util/FileUtil.java
+++ b/src/main/java/com/product/file/util/FileUtil.java
@@ -33,6 +33,43 @@
 	private FileUtil() {
 	}
 
+	public static String checkDocType(File file) {
+		try (FileInputStream fis = new FileInputStream(file)) {
+			byte[] bytes = new byte[8];
+			fis.read(bytes, 0, 8);
+
+			String hex = bytesToHex(bytes);
+
+			if (hex.contains("504B0304") && (file.getName().endsWith(".doc") || file.getName().endsWith(".docx"))) {
+				return "docx";
+			} else if (hex.contains("D0CF11E0") && (file.getName().endsWith(".doc") || file.getName().endsWith(".docx"))) {
+				//鍥犱负doc鏂囦欢鐨勫ご閮ㄤ篃鏄疍0CF11E0锛屾墍浠ラ渶瑕佸垽鏂枃浠跺悗缂�
+				return "doc";
+			}
+			//澧炲姞xls 鍜� xlsx鐨勫垽鏂�
+			else if (hex.contains("504B0304") && (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx"))) {
+				return "xlsx";
+			} else if (hex.contains("D0CF11E0") && (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx"))) {
+				//鍥犱负xls鏂囦欢鐨勫ご閮ㄤ篃鏄疍0CF11E0锛屾墍浠ラ渶瑕佸垽鏂枃浠跺悗缂�
+				return "xls";
+			} else {
+				return "unknown";
+			}
+		} catch (
+				IOException e) {
+			e.printStackTrace();
+			return "unknown";
+		}
+	}
+
+	private static String bytesToHex(byte[] bytes) {
+		StringBuilder hex = new StringBuilder();
+		for (byte b : bytes) {
+			hex.append(String.format("%02X", b));
+		}
+		return hex.toString();
+	}
+
 	/**
 	 * 鍚堝苟word鏂囨。
 	 *
@@ -41,16 +78,13 @@
 	 * @return
 	 */
 	public static File mergeFile(File source, File target) throws Exception {
-		//鍒ゆ柇鏂囦欢鏄惁涓� docx鎴杁oc鏍煎紡
-		if (!source.getName().endsWith(".docx") && !source.getName().endsWith(".doc")) {
-			throw new BaseException(FileCode.ADD_FILE_NOT_ALLOWED);
-		}
-		//濡傛灉鏄痙oc鏍煎紡鍒欒浆鎹负docx鏍煎紡
-		if (source.getName().endsWith(".doc")) {
+		if ("doc".equals(FileUtil.checkDocType(source))) {
 			source = toDocx(source);
 		}
-		if (target.getName().endsWith(".doc")) {
+		boolean delTarget = false;
+		if ("doc".equals(FileUtil.checkDocType(target))) {
 			target = toDocx(target);
+			delTarget = true;
 		}
 		XWPFTemplate template = XWPFTemplate.compile(source);
 		NiceXWPFDocument xwpfDocument = template.getXWPFDocument();
@@ -65,6 +99,9 @@
 			} catch (IOException e) {
 				throw e;
 			} finally {
+				if (delTarget) {
+					target.delete();
+				}
 				newDoc.close();
 				sub.close();
 			}
@@ -83,8 +120,9 @@
 		File docxFile = new File(file.getParent() + File.separator + docxName);
 		String tempDir = Global.getSystemConfig("temp.dir", "./attachment/temp");
 		File tempFile = new File(tempDir + File.separator + docxName);
-		try {
-			Document document = new Document(new FileInputStream(file));
+
+		try (FileInputStream is = new FileInputStream(file);) {
+			Document document = new Document(is);
 			document.save(tempFile.getAbsolutePath(), com.aspose.words.SaveFormat.DOCX);
 			return tempFile;
 		} catch (Exception e) {

--
Gitblit v1.9.2