java程式碼自動啟動OpenOffice
阿新 • • 發佈:2022-05-27
前言
之前用openOffice將docx轉pdf實現線上預覽,但每次都要自己手動cmd啟動,看網上教程說可以下載Server 2003 Resource Kit Tools來自啟動OpenOffice,但是這個連線已經失效並且下載不了了,就選擇採取用java程式碼來啟動OpenOffice,就只要我們電腦安裝了openOffice就可以啦。
方法
* 在FileConvertUtil
里加兩個方法
//啟動OpenOffice servicePath 是OpenOffice的安裝路徑 public static void startOpenOfficeService(String servicePath) { String command = servicePath + "program\\soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard"; try { Process pro = Runtime.getRuntime().exec(command); } catch (IOException e) { System.out.println("OpenOffice服務啟動失敗"); } } /** *關閉OpenOffice **/ public static void shutdownOpenOfficeService() { try { Process pro = Runtime.getRuntime().exec("tasklist"); Scanner in = new Scanner(pro.getInputStream()); while(in.hasNext()) { String proString = in.nextLine(); if(proString.contains("soffice.exe")) { String cmd = "taskkill /f /im soffice.exe"; pro = Runtime.getRuntime().exec(cmd); System.out.println("soffice.exe關閉"); } if(proString.contains("soffice.bin")) { String cmd = "taskkill /f /im soffice.bin"; pro = Runtime.getRuntime().exec(cmd); System.out.println("soffice.bin關閉"); } } } catch (IOException e) { e.printStackTrace(); } }
* 業務層程式碼調這個方法
//servicePath 是OpenOffice的安裝路徑 private static final String servicePath = "C:\\Program Files (x86)\\OpenOffice 4\\"; //線上預覽 public OutputStream onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception { //獲取檔案型別 String suffix = url.substring(url.lastIndexOf('.') + 1); if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls") && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx") && !suffix.equals("sheet") && !suffix.equals("pdf")) { throw new Exception("檔案格式不支援預覽"); } url = url.replace(STORE_PATH, LOCAL_STORE_PATH); InputStream in = null; //如果是pdf檔案,則不用轉,直接展示 if (suffix.equals("pdf")) { in = new BufferedInputStream(new FileInputStream(url)); } else { //docx檔案則先啟動openOffice FileConvertUtil.startOpenOfficeService(servicePath); in = FileConvertUtil.convertLocaleFile(url, suffix); //關閉openOffice FileConvertUtil.shutdownOpenOfficeService(); } // url = String.format("http://"+url); OutputStream outputStream = response.getOutputStream(); //建立存放檔案內容的陣列 byte[] buff = new byte[1024]; //所讀取的內容使用n來接收 int n; //當沒有讀取完時,繼續讀取,迴圈 while ((n = in.read(buff)) != -1) { //將位元組陣列的資料全部寫入到輸出流中 outputStream.write(buff, 0, n); } //強制將快取區的資料進行輸出 outputStream.flush(); //redisTemplate.opsForValue().set("Knowledge:" + url, outputStream.toString()); //關流 outputStream.close(); in.close(); return outputStream; }
ok!