一、重要轉換代碼:
@Override public void transform(InputStream in, OutputStream out, String fileName) throws IOException { UUID uuid = UUID.randomUUID(); this.cacheFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + uuid; // 設置本地緩存的路徑
String tmpPath = localHtmlCachePath + IOUtils.DIR_SEPARATOR + this.cacheFileName + ".pdf"; String lowerFileName = fileName.toLowerCase(); try { if (!new File(tmpPath).exists()) { if (lowerFileName.endsWith(".xls") || lowerFileName.endsWith(".xlsx") || lowerFileName.endsWith(".csv")) { com.aspose.cells.Workbook workbook = new com.aspose.cells.Workbook(in); workbook.save(tmpPath, com.aspose.cells.SaveFormat.PDF); } else if (lowerFileName.endsWith(".doc") || lowerFileName.endsWith(".docx") || lowerFileName.endsWith(".rtf")) { com.aspose.words.Document doc = new com.aspose.words.Document(in); doc.save(tmpPath, com.aspose.words.SaveFormat.PDF); } else if (lowerFileName.endsWith(".ppt") || lowerFileName.endsWith(".pptx") || lowerFileName.endsWith(".pps") || lowerFileName.endsWith(".ppsx")) { com.aspose.slides.Presentation ppt = new com.aspose.slides.Presentation(in); ppt.save(tmpPath, com.aspose.slides.SaveFormat.Pdf); } else if (lowerFileName.endsWith(".vdx") || lowerFileName.endsWith(".vsx") || lowerFileName.endsWith(".vtx") || lowerFileName.endsWith(".vsd") || lowerFileName.endsWith(".vsdx")) { com.aspose.diagram.Diagram visio = new com.aspose.diagram.Diagram(in); visio.save(tmpPath, com.aspose.diagram.SaveFileFormat.PDF); } else if (lowerFileName.endsWith(".pdf")) { com.aspose.pdf.Document pdf = new com.aspose.pdf.Document(in); pdf.save(tmpPath, com.aspose.pdf.SaveFormat.Pdf); } } if (out instanceof ResponseOutputStream) { HttpServletResponse response = ((ResponseOutputStream) out).getResponse(); response.sendRedirect("/filePreview/officeHtmlFileViwer/" + this.cacheFileName + ".pdf"); } } catch (Exception ex) { throw new RuntimeException(ex); } }
二、創建了一個maven 項目,用到的相關jar如下:

三、遇到問題:
1、緩存文件夾不存在則創建:
// 文件夾不存在則創建
if (!new File(localHtmlCachePath).exists()) { new File(localHtmlCachePath).mkdirs(); }
2、有水印:獲取lic有問題:不能圖省事,要以此次的獲取InputStream(setLicense方法執行完可能是把InputStream給close了)

3、response.sendRedirect("/preview/officeHtmlFileViwer/" + this.cacheFileName + ".html");執行之后沒有打開新頁面
原因:不能close,因為還有請求在跑。

