用openoffice+jodconverter+webuploader+pdf.js實現文件上傳、在線預覽功能


一、背景

  最近公司一個項目要實現一個文件上傳以及多文檔在線預覽的功能,之前一直做無線工具開發的,沒有涉及到這些東西。另外項目組缺java開發人員,而且自己也只是一個半吊子前端加小半吊子java開發人員,所以讓我一個人先弄個Demo出來瞧瞧。在網上搜索了不少資料,在這里只是整理一下,留作以后查閱。

二、插件以及工具包

  1.pdfjs-v1.7.225  前端pdf格式文件的顯示組件

  2.webuploader-0.1.5  百度的文件上傳組件

  3.video-js-6.2.5 html5視頻播放組件

  4.openoffice-4.1.3 本地安裝的,這里主要用於文檔轉pdf的程序

  5.jodconverter-core 3.0-beta-4 java調用openoffice的包

  其中pdfjs可以用ViewerJS來代替,后者相對於是對前者的封裝。另外java包jodconverter也可以用com.artofsolving.jodconverter.2.2.1來代替,根據網上別人說的以及自己小小測試了一下jodconverter.2.2.1也轉換pdf的時候要快那么一點點,但是卻不支持office2003之后的docx/xlsx/pptx這些文件類型,說是要定制java代碼也可以實現支持,本來比較懶也就棄用了。

三、代碼

  廢話說了一大堆先上前端代碼,由於是Demo,代碼寫的很糙;

  1.主要頁面index.html 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>文件預覽Demo</title>
 8     <!-- jquery -->
 9     <script src="./plugIns/jquery-3.2.1.min.js"></script>
10     <!-- bootstrap -->
11     <link rel="stylesheet" href="./plugIns/bootstrap-3.3.7/css/bootstrap.min.css">
12     <script src="./plugIns/bootstrap-3.3.7/js/bootstrap.min.js" charset="utf-8"></script>
13     <!-- webuploader -->
14     <link rel="stylesheet" type="text/css" href="./plugIns/webuploader-0.1.5/webuploader.css">
15     <script type="text/javascript" src="./plugIns/webuploader-0.1.5/webuploader.min.js"></script>
16     <!-- font-awesome -->
17     <link rel="stylesheet" href="./plugIns/font-awesome-4.7.0/css/font-awesome.min.css">
18     <link rel="stylesheet" href="./css/filepreview/preview.css">
19 </head>
20 
21 <body>
22     <div class="container" style="padding-top:150px;">
23         <div>
24             <div class="list">
25 
26             </div>
27         </div>
28         <div id="uploader" class="wu-example">
29             <!--用來存放文件信息-->
30             <div id="thelist" class="uploader-list"></div>
31             <div class="btns">
32                 <div id="picker">選擇文件</div>
33                 <button id="ctlBtn" class="btn btn-default">開始上傳</button>
34             </div>
35         </div>
36     </div>
37     <div class="load">
38         <img src="./images/loading.gif" alt="">
39     </div>
40 </body>
41 <script src="./js/filepreview/preview.js" charset="utf-8"></script>
42 <script src="./js/filepreview/upload.js" charset="utf-8"></script>
43 </html>

  2.控制文件上傳的upload.js

 1 $(function() {
 2     var $list = $('#thelist'),
 3         $btn = $('#ctlBtn'),
 4         state = 'pending';
 5     var uploader = WebUploader.create({
 6         // swf文件路徑
 7         swf: './plugIns/webuploader-0.1.5/Uploader.swf',
 8         // 文件接收服務端。
 9         server: '/file/upload',
10         // 選擇文件的按鈕。可選。
11         // 內部根據當前運行是創建,可能是input元素,也可能是flash.
12         pick: '#picker',
13         // 不壓縮image, 默認如果是jpeg,文件上傳前會壓縮一把再上傳!
14         resize: false,
15         // 開起分片上傳。
16         chunked: true,
17         //fileSingleSizeLimit: 10*1024*1024,//限制大小10M,單文件
18         //fileSizeLimit: allMaxSize*1024*1024,//限制大小10M,所有被選文件,超出選擇不上
19         //設置允許上傳的文件類型,不過點擊選擇文件的時候會很卡
20         // accept: {
21         //     title: 'Images',
22         //     extensions: 'jpg,png',
23         //     mimeTypes: 'image/*'
24         // }
25     });
26     // 當有文件被添加進隊列的時候
27     uploader.on('fileQueued', function(file) {
28         let typeList = ['png', 'jpg', 'txt', 'xls', 'doc', 'ppt', 'pdf', 'mp4','docx','pptx','xlsx'];
29         if(!typeList.includes(file.name.split('.')[1])){
30             alert("不支持的文件類型!");
31             uploader.removeFile( file );
32             return;
33         }
34 
35 
36         $list.append('<div id="' + file.id + '" class="item">' +
37             '<h4 class="info">' + file.name + '</h4>' +
38             '<p class="state">等待上傳...</p>' +
39             '</div>');
40     });
41     // 文件上傳過程中創建進度條實時顯示。
42     uploader.on('uploadProgress', function(file, percentage) {
43         var $li = $('#' + file.id),
44             $percent = $li.find('.progress .progress-bar');
45 
46         // 避免重復創建
47         if (!$percent.length) {
48             $percent = $('<div class="progress progress-striped active">' +
49                 '<div class="progress-bar" role="progressbar" style="width: 0%">' +
50                 '</div>' +
51                 '</div>').appendTo($li).find('.progress-bar');
52         }
53 
54         $li.find('p.state').text('上傳中');
55 
56         $percent.css('width', percentage * 100 + '%');
57     });
58     uploader.on('uploadSuccess', function(file) {
59         getFileList();
60         $('#' + file.id).find('p.state').text('已上傳');
61     });
62 
63     uploader.on('uploadError', function(file) {
64         $('#' + file.id).find('p.state').text('上傳出錯');
65     });
66 
67     uploader.on('uploadComplete', function(file) {
68         $('#' + file.id).find('.progress').fadeOut();
69     });
70 
71     uploader.on('all', function(type) {
72         if (type === 'startUpload') {
73             state = 'uploading';
74         } else if (type === 'stopUpload') {
75             state = 'paused';
76         } else if (type === 'uploadFinished') {
77             state = 'done';
78         }
79 
80         if (state === 'uploading') {
81             $btn.text('暫停上傳');
82         } else {
83             $btn.text('開始上傳');
84         }
85     });
86 
87     $btn.on('click', function() {
88         if (state === 'uploading') {
89             uploader.stop();
90         } else {
91             uploader.upload();
92         }
93     });
94 });

  3.負責預覽的preview.js

 1 $(function() {
 2     const typeList = ['png', 'jpg', 'txt', 'xls', 'doc', 'ppt', 'pdf','docx','pptx','xlsx'];
 3     getFileList = function() {
 4         $(".list").empty();
 5         $.get("/file/list", function(data) {
 6             data = JSON.parse(data);
 7             for (let file of data) {
 8                 let htmlStr = '<a class="point file" data-file="' + file.name + '" data-size="' + file.size + '" data-type="'+ file.type +'">';
 9                 if (file.type.toLowerCase() == 'png' || file.type.toLowerCase() == 'jpg') {
10                     htmlStr = '<a class="file" target="_blank" href="./filelist/' + file.name + '">';
11                 } else if (file.type.toLowerCase() == 'pdf') {
12                     htmlStr = '<a class="file" target="_blank" href="http://localhost:8080/plugIns/pdfjs/web/viewer.html?file=../../../../filelist/' + file.name + '">';
13                 } else if (file.type.toLowerCase() == 'mp4') {
14                     htmlStr = '<a class="file" target="_blank" href="video?path=../../filelist/' + file.name + '">';
15                 }
16                 let imgName = file.type=='docx'||file.type=='xlsx'||file.type=='pptx'?file.type.substr(0,file.type.length-1):file.type;
17                 $(".list").append(
18                     '<div class="col-xs-6 col-md-2">' + htmlStr +
19                     '<embed src="./images/svg/' + imgName + '.svg" type="image/svg+xml" /><span>' + file.name +
20                     '</span></a>&nbsp;<i class="fa fa-eye"></i>&nbsp;<span class="number">'+file.number+'</span></div>'
21                 );
22             }
23         });
24     }
25     getFileList();
26 
27     /**
28      * 無法直接查看的文件,需要server先進行轉換
29      */
30     $(".list").on("click", ".point", function() {
31         let date = new Date().getTime();
32         let param = $(this).data("file");
33         let type = $(this).data("type");
34         if (typeList.indexOf(type)==-1) {
35             alert("暫不支持預覽的文件類型!");
36             return;
37         }
38         if ($(this).data("size") >= 11534336) {
39             alert("文件太大,暫不支持預覽!");
40             return;
41         }
42         $('.load').addClass('active');
43         $.ajax({
44             type: 'post',
45             url: '/file/preview',
46             data: param,
47             contentType: 'application/json',
48             dataType: 'text',
49             success: function(data) {
50                 $('.load').removeClass('active');
51                 console.log("轉換耗時===>" + (new Date().getTime() - date) + "ms");
52                 window.open("http://localhost:8080/plugIns/pdfjs/web/viewer.html?file=../../../../filelist/temp/" + data + ".pdf");
53             },
54             error: function(error) {
55                 $('.load').removeClass('active');
56                 alert("error!");
57             }
58         });
59     });
60 
61     /**
62      * 查看文件,瀏覽量累加
63      */
64     $(".list").on("click", ".file", function() {
65         let nSpan = $(this).parent().find('.number');
66         nSpan.text(nSpan.text()/1+1);
67     });
68 });

  4.播放mp4格式的video.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title></title>
 9     <link rel="stylesheet" href="/plugIns/video-js-6.2.5/video-js.min.css">
10     <!-- If you'd like to support IE8 -->
11     <script src="/plugIns/jquery-3.2.1.min.js"></script>
12     <script src="/plugIns/video-js-6.2.5/ie8/videojs-ie8.min.js" charset="utf-8"></script>
13     <script src="/Global.js" charset="utf-8"></script>
14     <style media="screen">
15         .videoCont {
16             padding-top: 150px;
17         }
18     </style>
19 </head>
20 
21 <body>
22     <div class="videoCont">
23         <video id="my-video" class="video-js" controls preload="auto" width="720" height="480" poster="MY_VIDEO_POSTER.jpg" data-setup="{}">
24             <source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
25             <!-- <source src="http://vjs.zencdn.net/v/oceans.webm" type="video/webm">
26             <source src="/filelist/Wildlife.wmv" type="video/wmv"> -->
27             <p class="vjs-no-js">
28                 To view this video please enable JavaScript, and consider upgrading to a web browser that
29                 <a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
30             </p>
31         </video>
32     </div>
33     <script src="/plugIns/video-js-6.2.5/video.min.js" charset="utf-8"></script>
34     <script type="text/javascript">
35         let wWidth = document.body.clientWidth;
36         $('.videoCont').css('padding-left',(wWidth-$('#my-video').attr("width"))/2);
37         let path = Global.getParamByKey("path");
38         $("#my-video source[type='video/mp4']").attr("src",path);
39         var myPlayer = videojs('my-video');
40         videojs("my-video").ready(function() {
41             var myPlayer = this;
42             myPlayer.play();
43         });
44     </script>
45 </body>
46 
47 </html>

  5.pom.xml

 1 <dependencies>
 2         <!-- Spring Boot web依賴 -->
 3         <dependency>
 4             <groupId>org.springframework.boot</groupId>
 5             <artifactId>spring-boot-starter-web</artifactId>
 6         </dependency>
 7 
 8         <!-- Junit -->
 9         <dependency>
10             <groupId>junit</groupId>
11             <artifactId>junit</artifactId>
12             <version>4.12</version>
13         </dependency>
14         <dependency>
15             <groupId>org.apache.commons</groupId>
16             <artifactId>commons-lang3</artifactId>
17             <version>3.6</version>
18         </dependency>
19         <!-- openoffice -->
20         <dependency>
21             <groupId>org.quartz-scheduler</groupId>
22             <artifactId>quartz</artifactId>
23             <version>2.3.0</version>
24         </dependency>
25         <!-- 不支持03之后的office -->
26         <dependency>
27             <groupId>com.artofsolving</groupId>
28             <artifactId>jodconverter</artifactId>
29             <version>2.2.1</version>
30         </dependency>
31         <!-- 支持03之后的office -->
32         <dependency>
33             <groupId>org.artofsolving.jodconverter</groupId>
34             <artifactId>jodconverter-core</artifactId>
35             <version>3.0-beta-4</version>
36         </dependency>
37         <dependency>
38             <groupId>org.openoffice</groupId>
39             <artifactId>jurt</artifactId>
40             <version>3.0.1</version>
41         </dependency>
42         <dependency>
43             <groupId>org.openoffice</groupId>
44             <artifactId>ridl</artifactId>
45             <version>3.0.1</version>
46         </dependency>
47         <dependency>
48             <groupId>org.openoffice</groupId>
49             <artifactId>juh</artifactId>
50             <version>3.0.1</version>
51         </dependency>
52         <dependency>
53             <groupId>org.openoffice</groupId>
54             <artifactId>unoil</artifactId>
55             <version>3.0.1</version>
56         </dependency>
57 
58         <!--jodconverter2.2.1必須依賴slf4j-jdk14必須這個版本,不然源碼中日志會報錯,很low的一個問題 -->
59         <dependency>
60             <groupId>org.slf4j</groupId>
61             <artifactId>slf4j-jdk14</artifactId>
62             <version>1.4.3</version>
63         </dependency>
64 
65         <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
66         <dependency>
67             <groupId>com.alibaba</groupId>
68             <artifactId>fastjson</artifactId>
69             <version>1.2.35</version>
70         </dependency>
71 
72         <dependency>
73             <groupId>commons-fileupload</groupId>
74             <artifactId>commons-fileupload</artifactId>
75             <version>1.3.1</version>
76         </dependency>
77     </dependencies>

  6.文檔轉pdf格式的工具類Office2PdfUtil

 1 package org.spring.springboot.util;
 2 
 3 import java.io.File;
 4 import java.util.regex.Pattern;
 5 
 6 import org.artofsolving.jodconverter.OfficeDocumentConverter;
 7 import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
 8 import org.artofsolving.jodconverter.office.OfficeManager;
 9 
10 public class Office2PdfUtil {
11 
12     private static Office2PdfUtil office2PdfUtil = new Office2PdfUtil();
13     private static OfficeManager officeManager;
14     // 服務端口
15     private static int OPEN_OFFICE_PORT[] = { 8100, 8101, 8102, 8103 };
16 
17     public static Office2PdfUtil getOffice2PdfUtil() {
18         return office2PdfUtil;
19     }
20 
21     /**
22      * 
23      * office2Pdf 方法
24      * 
25      * @descript:TODO
26      * @param inputFile
27      *            文件全路徑
28      * @param pdfFilePath
29      *            pdf文件全路徑
30      * @return void
31      */
32     public static void office2Pdf(File inputFile, File pdfFile) {
33 
34         try {
35             // 打開服務
36             startService();
37             OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
38             // 開始轉換
39             converter.convert(inputFile, pdfFile);
40             // 關閉
41             stopService();
42             System.out.println("運行結束");
43         } catch (Exception e) {
44             // TODO: handle exception
45             e.printStackTrace();
46         }
47     }
48 
49     public static void stopService() {
50         if (officeManager != null) {
51             officeManager.stop();
52         }
53     }
54 
55     public static void startService() {
56         DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
57         try {
58             configuration.setOfficeHome(getOfficeHome());// 設置安裝目錄
59             configuration.setPortNumbers(OPEN_OFFICE_PORT); // 設置端口
60             configuration.setTaskExecutionTimeout(1000 * 60 * 5L);
61             configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
62             officeManager = configuration.buildOfficeManager();
63             officeManager.start(); // 啟動服務
64         } catch (Exception ce) {
65             System.out.println("office轉換服務啟動失敗!詳細信息:" + ce);
66         }
67     }
68 
69     /**
70      * openoffice的安裝路徑
71      * 
72      * @return
73      */
74     public static String getOfficeHome() {
75         String osName = System.getProperty("os.name");
76         if (Pattern.matches("Linux.*", osName)) {
77             return "/opt/openoffice.org3";
78         } else if (Pattern.matches("Windows.*", osName)) {
79             return "C:/Program Files (x86)/OpenOffice 4/";
80         } else if (Pattern.matches("Mac.*", osName)) {
81             return "/Application/OpenOffice.org.app/Contents";
82         }
83         return null;
84     }
85 }

  這里需要注意的是不需要手動去開啟系統中的openoffice,以上代碼運行的時候會自動開啟。

  private static int OPEN_OFFICE_PORT[] = { 8100, 8101, 8102, 8103 }; 這個是openoffice的端口,默認是 {8100} ,寫入多個是為了開啟多個Openoffice服務,加快多線程轉換的效率。
  
  7.接口類FileController
  1 package org.spring.springboot.web;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.util.ArrayList;
  6 import java.util.Iterator;
  7 
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 import org.spring.springboot.bean.FileBean;
 12 import org.spring.springboot.util.Office2PdfUtil;
 13 import org.springframework.web.bind.annotation.GetMapping;
 14 import org.springframework.web.bind.annotation.PostMapping;
 15 import org.springframework.web.bind.annotation.RequestBody;
 16 import org.springframework.web.bind.annotation.RequestMapping;
 17 import org.springframework.web.bind.annotation.RestController;
 18 import org.springframework.web.multipart.MultipartFile;
 19 import org.springframework.web.multipart.MultipartHttpServletRequest;
 20 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 21 
 22 import com.alibaba.fastjson.JSON;
 23 
 24 
 25 @RestController
 26 @RequestMapping("file")
 27 public class FileController {
 28 
 29     @GetMapping("list")
 30     public String getFileList() {
 31         return getFileName();
 32     }
 33 
 34     public static String getFileName() {
 35         String path = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\filelist"; // 路徑
 36         File f = new File(path);
 37         if (!f.exists()) {
 38             System.out.println(path + " not exists");
 39             return null;
 40         }
 41 
 42         ArrayList<FileBean> files = new ArrayList<>();
 43 
 44         File fa[] = f.listFiles();
 45         for (File fs : fa) {
 46             if (fs.isFile()) {
 47                 FileBean fb = new FileBean(fs.getName(), fs.getName().split("\\.")[1], String.valueOf(fs.length()));
 48                 files.add(fb);
 49             }
 50         }
 51         return JSON.toJSONString(files);
 52     }
 53 
 54     @PostMapping(value = "preview", produces = "application/json; charset=utf-8")
 55     public String getPreview(@RequestBody String fileName) throws IOException {
 56         String sysDir = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\filelist\\";
 57         File inputFile = new File(sysDir + fileName);
 58         String outputPath = sysDir + "temp";
 59         File temp = new File(outputPath);
 60         // 目錄不存在,創建目錄
 61         if (!temp.exists()) {
 62             temp.mkdir();
 63         }
 64         File outputFile = new File(
 65                 outputPath + "\\" + fileName.split("\\.")[0] + "_" + fileName.split("\\.")[1] + ".pdf");
 66         // 如果轉換后的文件已經存在那么不需要再次轉換
 67         if (outputFile.exists()) {
 68             return fileName.split("\\.")[0]+ "_" + fileName.split("\\.")[1];
 69         }
 70         //方法一:用com.artofsolving
 71         //OpenOfficeUtil.office2Pdf(inputFile, outputFile);
 72         //方法二:用org.artofsolving
 73         Office2PdfUtil.office2Pdf(inputFile, outputFile);
 74         return fileName.split("\\.")[0]+ "_" + fileName.split("\\.")[1];
 75     }
 76 
 77     @RequestMapping("/upload")
 78     public String upload2(HttpServletRequest request, HttpServletResponse response)
 79             throws IllegalStateException, IOException {
 80         // 創建一個springmvc上傳文件解析器
 81         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
 82         // 判斷 request 是否有文件上傳,即多部分請求
 83         if (multipartResolver.isMultipart(request)) {
 84             // 轉換成多部分request
 85             MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
 86             // 取得request中的所有文件名
 87             Iterator<String> iter = multiRequest.getFileNames();
 88             while (iter.hasNext()) {
 89                 // 記錄上傳過程起始時的時間,用來計算上傳時間
 90                 int pre = (int) System.currentTimeMillis();
 91                 // 取得上傳文件
 92                 MultipartFile file = multiRequest.getFile(iter.next());
 93                 if (file != null) {
 94                     // 取得當前上傳文件的文件名稱
 95                     String myFileName = file.getOriginalFilename();
 96                     // 如果名稱不為“”,說明該文件存在,否則說明該文件不存在
 97                     if (myFileName.trim() != "") {
 98                         System.out.println(myFileName);
 99                         // 重命名上傳后的文件名
100                         // String fileName = "demoUpload" + file.getOriginalFilename();
101                         // 定義上傳路徑
102                         String path = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\filelist\\"
103                                 + myFileName;
104                         File localFile = new File(path);
105                         try {
106                             file.transferTo(localFile);
107                         } catch (IOException e) {
108                             e.printStackTrace();
109                         }
110                     }
111                 }
112                 // 記錄上傳該文件后的時間
113                 int finaltime = (int) System.currentTimeMillis();
114                 System.out.println(finaltime - pre);
115             }
116         }
117         return "/success";
118     }
119 }

  8.最后一個和Demo沒有關系,完全就是一個多線程轉換pdf的一個測試

 1 package org.spring.springboot;
 2 
 3 import java.io.File;
 4 import java.net.ConnectException;
 5 import java.util.concurrent.CountDownLatch;
 6 
 7 import org.spring.springboot.util.Office2PdfUtil;
 8 import org.spring.springboot.util.OpenOfficeUtil;
 9 
10 public class Main extends Thread {
11     private int index;
12     private CountDownLatch latch;
13 
14     public Main(int index, CountDownLatch latch) {
15         this.index = index;
16         this.latch = latch;
17     }
18 
19     @Override
20     public void run() {
21         super.run();
22         String str = String.format("5m_%s.doc", index);
23         long time = System.currentTimeMillis();
24         work(str);
25         latch.countDown();
26         System.out.println(String.format("文件%s解析耗時:%sms", str, String.valueOf(System.currentTimeMillis() - time)));
27     }
28 
29     public static void main(String[] args) {
30         CountDownLatch latch = new CountDownLatch(50);
31         Office2PdfUtil.startService();
32         for (int i = 1; i < 51; i++) {
33             new Main(i, latch).start();
34         }
35         try {
36             long time = System.currentTimeMillis();
37             System.out.println(String.format("開始"));
38             latch.await();
39             Office2PdfUtil.stopService();
40             System.out.println(String.format("所有文件解析耗時:%sms", String.valueOf(System.currentTimeMillis() - time)));
41         } catch (InterruptedException e) {
42             // TODO Auto-generated catch block
43             e.printStackTrace();
44         }
45     }
46 
47     public static void work(String fileName) {
48         String sysDir = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\test\\";
49         File inputFile = new File(sysDir + fileName);
50         String outputPath = sysDir + "temp";
51         File outputFile = new File(
52                 outputPath + "\\" + fileName.split("\\.")[0] + "_" + fileName.split("\\.")[1] + ".pdf");
53         Office2PdfUtil.office2Pdf(inputFile, outputFile);
54     }
55 
56 }
  CountDownLatch可以監測多線程運行結束。第30、32行的數字是設置解析的文件數量。
  
  9.python生成多個有內容的文件代碼也一並奉上
 1 #-*-coding:utf-8-*-
 2 def gen_file(path,size):
 3     #首先以路徑path新建一個文件,並設置模式為寫
 4     file = open(path,'w')
 5     #根據文件大小,偏移文件讀取位置
 6     file.seek(1024*1024*size)#姑且以MB為單位吧
 7     #然后在當前位置寫入任何內容,必須要寫入,不然文件不會那么大哦
 8     file.write('\x00')
 9     file.close()
10 
11 
12 
13 for i in range(100):
14     gen_file('E:/5m_'+str(i+1)+'.doc',5)  
以上都是測試代碼,項目中這么寫是要挨批的。完全是為了做個筆記,免得下次又要到處找。

四、頁面

 

這里面坑確實不少,不過我覺得主要在於pdf轉換這一步:
1.jodconverter-core 3.0-beta-4 這個包的maven依賴貌似下載不了
2.com.artofsolving.jodconverter與org.artofsolving.jodconverter這兩個包傻傻分不清
3.openoffice免費的嘛,你懂得,轉換效率不敢恭維,慢得很,而且並發支持並不好
4.用com.artofsolving.jodconverter的話轉換幾十個文件,動不動就沒有規律的會卡着不動,等半個小時依然沒有反應,必須殺掉openoffice進程才能重來,試了很多次,org.artofsolving.jodconverter沒有發現這個問題。
5.多個文檔轉換的時候,打開openoffice服務和關閉openoffice服務都只需要調用一次。不然每次都開開關關的很無語。


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM