fastDFS+LibreOffice檔案預覽(四):轉為pdf格式線上預覽
阿新 • • 發佈:2018-12-22
注意:
1)需要下載LibreOffice
2)括號裡的LibreOffice是這個程式的安裝位置
// 連線OpenOffice/LibreOffice服務 此地址為服務端安裝專案路徑,本地需要自行安裝libreoffice
OfficeManager officeManager = LocalOfficeManager.builder().officeHome(LibreOffice)
.install().build();
/* 本地LibreOffice的儲存位置 */ public static final String LibreOffice = "C:\\Program Files (x86)\\LibreOffice";
3)預覽功能的後臺程式碼
/** * 預覽 * @param fileInfo * @param response * @throws Exception */ @RequestMapping(value = "preview") public void preview(FileInfo fileInfo, HttpServletResponse response) throws Exception { response.setContentType("application/pdf"); // 設定返回檔名 response.setHeader("Content-Disposition", "inline; filename=" + new String((fileInfo.getFileName() + ".pdf").getBytes("UTF8"), "ISO8859_1")); try { // 從fastdfs中獲取實際檔案 byte[] fileByte = fastDFSTemplate.loadFile(fileInfo.getFdfsGroup(),fileInfo.getFdfsPath()); // 輸出流 OutputStream out = response.getOutputStream(); // 是PDF就直接輸出 if ("PDF".equalsIgnoreCase(fileInfo.getFdfsPath().substring(fileInfo.getFdfsPath().indexOf(".")))){ // 直接輸出 out.write(fileByte); } // 不是就做轉換 else { InputStream byteArrayInputStream = new ByteArrayInputStream(fileByte); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 此方法不能多執行緒使用 synchronized (LocalOfficeManager.class) { // 連線OpenOffice/LibreOffice服務 此地址為服務端安裝專案路徑,本地需要自行安裝libreoffice OfficeManager officeManager = LocalOfficeManager.builder().officeHome(LibreOffice) .install().build(); try { // 服務啟動 officeManager.start(); // 轉換文件到pdf long time = System.currentTimeMillis(); // 轉換格式,注意:execute必須要用到,此為轉換 JodConverter.convert(byteArrayInputStream).as(fileInfo.getType()).to(byteArrayOutputStream) .as(DefaultDocumentFormatRegistry.PDF).execute(); System.out.println("convert used :" + (System.currentTimeMillis() - time) + "ms"); // 輸出 out.write(byteArrayOutputStream.toByteArray()); } catch (OfficeException e) { e.printStackTrace(); } finally { try { officeManager.stop(); } catch (OfficeException e) { e.printStackTrace(); } } } } out.flush(); out.close(); } catch (FastDFSException e) { e.printStackTrace(); } }
4)預覽功能的前端程式碼
不建議用<button/>,用<input type="button"/>代替。
<input type="button" onclick="preview('${attachment.fileName}','${attachment.ext}','${attachment.fdfsGroup}','${attachment.fdfsPath}')"
class="previewButton fontTypeTwo" value="預覽"/>
JS部分
/* 下載 */ function download(fileName,fdfsGroup,fdfsPath) { location.href ="${ctx}/info/notice/download?fileName="+fileName+"&fdfsGroup="+fdfsGroup+"&fdfsPath="+fdfsPath; }