shichongfu
2023-06-19 d67cc1b3c08a2a7c5212e51c9776d095b4503b0a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
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.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
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.*;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
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;
    //是否初始了license
    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) {
                try {
                    is.close();
                }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) {
                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{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }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));
            }
//            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) {
                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);
        }
    }
    /**
     * 
     * @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.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) {
                    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) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }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,如果已转为PDF就不需要再次转换。
        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);
//                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) {
 
        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,如果已转为PDF就不需要再次转换。
        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{
        
        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);
                targetDoc.save(out, SaveFormat.DOCX);
            }
        }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(out!=null) {
                    out.flush();
                    out.close();
                }
            }catch(IOException e) {
                throw new BaseException(FileCode.DOC_MERGE_FALL,e);
            }
        }
        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();
        }
        
    }
 
    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()+" | 源文档页数:"+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();
        }
    }
}