许鹏程
2025-02-10 ef26bf4fde77ba361bcd083a769c3a1b8a229738
src/main/java/com/product/file/util/AsposeUtil.java
@@ -1,27 +1,26 @@
package com.product.file.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.cells.*;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.SaveFormat;
import com.aspose.words.*;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.file.config.FileCode;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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;
   //是否初始了license
   private static boolean isInitLicense = false;
@@ -38,20 +37,26 @@
      boolean result = true;
      InputStream is = null;
      try {
         is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
         com.aspose.cells.License excel = new com.aspose.cells.License();
         excel.setLicense(is);
         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);
         is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
         com.aspose.slides.License ppt = new com.aspose.slides.License();
         ppt.setLicense(is);
         isInitLicense = true;
            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 {
@@ -79,8 +84,8 @@
      FileOutputStream fileOS = null;
      try {
         File file = new File(OutPutPath);
         if (!file.exists()) {
            file.mkdirs();
         if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
         }
         Workbook wb = new Workbook(officePath);// 原始excel路径
         fileOS = new FileOutputStream(OutPutPath);
@@ -88,6 +93,43 @@
         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) {
               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 {
@@ -110,17 +152,19 @@
      FileOutputStream fileOS = null;
      try {
         File file = new File(OutPutPath);
         if (!file.exists()) {
            file.mkdirs();
         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));
            //setAutoWithHeight(sheets.get(i));
         }
//            HtmlSaveOptions options = new HtmlSaveOptions();
//            options.setPresentationPreference(true);
         fileOS = new FileOutputStream(OutPutPath);
         wb.save(fileOS, SaveFormat.HTML);
         wb.save(fileOS, com.aspose.cells.SaveFormat.HTML);
      } catch (Exception e) {
         throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
      } finally {
@@ -167,11 +211,13 @@
      FileOutputStream fileOS = null;
      try {
         File file = new File(OutPutPath);
         if (!file.exists()) {
            file.mkdirs();
         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);
@@ -200,8 +246,8 @@
      FileOutputStream fileOS = null;
      try {
         File PathFile = new File(OutPutPath);
         if (!PathFile.exists()) {
            PathFile.mkdirs();
         if (!PathFile.getParentFile().exists()) {
            PathFile.getParentFile().mkdirs();
         }
         InputStream slides = new FileInputStream(officePath);// 原始ppt路径
         Presentation pres = new Presentation(slides);
@@ -230,7 +276,7 @@
    * @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;
@@ -241,8 +287,9 @@
         if (officeType.equals("doc") || officeType.equals("docx")) {
            Word2Pdf(officePath, outFile);
         } else if (officeType.equals("xls") || officeType.equals("xlsx")) {
//                Excel2Pdf(officePath,outFile);
            Excel2Html(officePath, outFile);
                Excel2Pdf(officePath,outFile);
//            Excel2Html(officePath, outFile);
//                xls2xlsx(officePath,outFile,officeType);
         } else if (officeType.equals("ppt") || officeType.equals("pptx")) {
            PPT2Pdf(officePath, outFile);
         } else {
@@ -267,37 +314,21 @@
      int lastNameIndex = split[0].lastIndexOf("/");
      String officeType = split[0].substring(lastIndex + 1);
      String officeName = split[0].substring(lastNameIndex + 1, lastIndex) + ".pdf";
      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]);
      File pdfFile = new File(OutPutPath + officeName);
      //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
      if (pdfFile.exists()) {
         return OutPutPath + officeName;
      }
      if (file.exists()) {
         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) {
            return Size + "MB";
         }
         //"doc", "docx", "xls","xlsx", "ppt", "pptx"
         try {
            if (officeType.equals("doc") || officeType.equals("docx")) {
               Word2Pdf(split[0], OutPutPath + "/" + officeName);
               Word2Pdf(split[0], OutPutPath + "/" + officeName + ".pdf");
            } else if (officeType.equals("xls") || officeType.equals("xlsx")) {
               Excel2Pdf(split[0], OutPutPath + "/" + officeName);
//                   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);
               PPT2Pdf(split[0], OutPutPath + "/" + officeName + ".pdf");
            } else {
               System.out.println("无法识别该文件!");
               return "Error";
@@ -325,16 +356,11 @@
      return mergeWord(target, source);
   }
   public static void main(String args[]) {
      String file = "E:/work/沄崃/FE6.6产品报价工具-新 - 副本.xlsx";
      AsposeUtil.OfficeToPdf(file);
   }
   /**
    * word文档的合并
    *
    * @param targetWordFile
    * @param sourceWordFile
    * @param
    * @param
    * @return
    * @throws Exception
    */
@@ -348,7 +374,7 @@
         return source;
      }
      // 验证License
      if (!getLicense(2)) {
      if (!getLicense(OFFICE_WORD)) {
         return null;
      }
      FileInputStream tin = null;
@@ -361,16 +387,25 @@
         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);
            targetDoc.save(out, SaveFormat.DOCX);
         }
      } catch (Exception e) {
         e.printStackTrace();
         throw new BaseException(FileCode.DOC_MERGE_FALL, e);
      } finally {
         try {
@@ -390,4 +425,177 @@
      }
      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);
         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);
            }
         }
      }
      for (Node d : ss) {
         d.remove();
      }
   }
   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() + " | 源文档页数:" + srcDoc.getPageCount());
      if (includeSection) {
         Iterator<Section> var3 = srcDoc.getSections().iterator();
         while (var3.hasNext()) {
            Section srcSection = (Section) var3.next();
            Node dstNode = dstDoc.importNode(srcSection, true, 0);
            dstDoc.appendChild(dstNode);
         }
      } else {
         Node node = dstDoc.getLastSection().getBody().getLastParagraph();
         if (node == null) {
            node = new Paragraph(srcDoc);
            dstDoc.getLastSection().getBody().appendChild(node);
         }
         if (node.getNodeType() != 8 & node.getNodeType() != 5) {
            throw new Exception("Use appendDoc(dstDoc, srcDoc, true) instead of appendDoc(dstDoc, srcDoc, false)");
         }
         insertDocumentAfterNode(node, dstDoc, srcDoc);
      }
      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)
         throws Exception {
      if (insertAfterNode.getNodeType() != 8 & insertAfterNode.getNodeType() != 5) {
         throw new Exception("The destination node should be either a paragraph or table.");
      } else {
         CompositeNode dstStory = insertAfterNode.getParentNode();
         while (null != srcDoc.getLastSection().getBody().getLastParagraph()
               && !srcDoc.getLastSection().getBody().getLastParagraph().hasChildNodes()) {
            srcDoc.getLastSection().getBody().getLastParagraph().remove();
         }
         NodeImporter importer = new NodeImporter(srcDoc, mainDoc, 1);
         int sectCount = srcDoc.getSections().getCount();
         for (int sectIndex = 0; sectIndex < sectCount; ++sectIndex) {
            Section srcSection = srcDoc.getSections().get(sectIndex);
            int nodeCount = srcSection.getBody().getChildNodes().getCount();
            for (int nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex) {
               Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
               Node newNode = importer.importNode(srcNode, true);
               dstStory.insertAfter(newNode, insertAfterNode);
               insertAfterNode = newNode;
            }
         }
      }
   }
   /**
    * 把源文档内容放到最后一页的页末
    *
    * @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[]) {
//       String file="E:/工作内容.xlsx";
//       String file="E:/爆破母线.xls";
//       String file="E:/采集提取日志表结构.xlsx";
      String file = "E:/FE信息系统国产化解决方案V1.0.docx";
//       AsposeUtil.OfficeToPdf(file);
//       AsposeUtil.mergeWord("E:\\QQ\\住房担保置换公司.docx","E:\\QQ\\住房担保置换公司2.docx");
//       try {
//          processDocPage();
//       }catch(Exception e) {
//          e.printStackTrace();
//       }
      try {
//         String sohuyepath="E:/QQ/住房担保置换公司.docx";
//         String xuyepath="E:/QQ/FE信息系统国产化解决方案V1.0.docx";
//         String npath=appendDoc(sohuyepath, xuyepath, false);
         String tail = "E:/QQ/住房担保置换公司2.docx";
//            appendDoc(npath, tail, false);
         appendDocToPageTail(tail);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}