用JAVA实现word文档在线预览的功能

£神魔★判官ぃ 2024-04-01 06:11 239阅读 0赞

预览Word、PPT、Excel

我之前发过一篇文章,是介绍office预览和编辑的但是大部门插件都是收费的,我这次提供的是免费的一个将Word、PPT、Excel转换为PDF然后在浏览器进行预览,之前也看过很多网上的一些预览方案,比如openoffice、jacob、libreoffice等等,但是相对于速度以及bug容错来讲,用aspose是最简单最方便,直接jar包,然后代码抄走就行了。

jar包,跟相关xml我都放到我主页的下载资源中了,放到我服务器上的话,未来某一天服务器不用了,我这个文章岂不作废了,大家可以去我的主页下载资源,就是叫 使用aspose将office转换为PDF。

以下代码是我自己实际业务环境,大家可以自行修改,如有问题大家评论区讨论。

  1. package com.test;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. import java.math.RoundingMode;
  7. import java.text.DecimalFormat;
  8. import com.aspose.cells.PdfSaveOptions;
  9. import com.aspose.cells.Workbook;
  10. import com.aspose.slides.Presentation;
  11. import com.aspose.words.Document;
  12. import com.is.flywings.frame.util.Sysout;
  13. public class AsposeUtil {
  14. /**
  15. * 获取license
  16. *
  17. * @return
  18. */
  19. public static boolean getLicense(int type) {
  20. boolean result = false;
  21. try {
  22. InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
  23. if (type == 1) {
  24. //excel
  25. com.aspose.cells.License aposeLic = new com.aspose.cells.License();
  26. aposeLic.setLicense(is);
  27. result = true;
  28. } else if (type == 2) {
  29. //word
  30. com.aspose.words.License aposeLic = new com.aspose.words.License();
  31. aposeLic.setLicense(is);
  32. result = true;
  33. } else {
  34. //ppt
  35. com.aspose.slides.License aposeLic = new com.aspose.slides.License();
  36. aposeLic.setLicense(is);
  37. result = true;
  38. }
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. return result;
  43. }
  44. public static void Excel2Pdf(String officePath,String OutPutPath,String officeName) {
  45. // 验证License
  46. if (!getLicense(1)) {
  47. return;
  48. }
  49. try {
  50. File file = new File(OutPutPath);
  51. if (!file.exists()) {
  52. file.mkdirs();
  53. }
  54. // long old = Sysout.currentTimeMillis();
  55. Workbook wb = new Workbook(officePath);// 原始excel路径
  56. File pdfFile = new File(OutPutPath+officeName);// 输出路径
  57. FileOutputStream fileOS = new FileOutputStream(pdfFile);
  58. //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
  59. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
  60. pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
  61. wb.save(fileOS, pdfSaveOptions);
  62. // long now = Sysout.currentTimeMillis();
  63. // Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. public static void Word2Pdf(String officePath,String OutPutPath,String officeName) {
  69. // 验证License
  70. if (!getLicense(2)) {
  71. return;
  72. }
  73. try {
  74. File file = new File(OutPutPath);
  75. if (!file.exists()) {
  76. file.mkdirs();
  77. }
  78. Document doc = new Document(officePath);// 原始word路径
  79. File pdfFile = new File(OutPutPath+officeName);// 输出路径
  80. FileOutputStream fileOS = new FileOutputStream(pdfFile);
  81. doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. }
  85. }
  86. public static void PPT2Pdf(String officePath,String OutPutPath,String officeName) {
  87. // 验证License
  88. if (!getLicense(3)) {
  89. return;
  90. }
  91. try {
  92. File PathFile = new File(OutPutPath);
  93. if (!PathFile.exists()) {
  94. PathFile.mkdirs();
  95. }
  96. InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径
  97. Presentation pres = new Presentation(slides);
  98. File file = new File(OutPutPath+officeName);// 输出pdf路径
  99. FileOutputStream fileOS = new FileOutputStream(file);
  100. pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
  101. } catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. }
  105. public static String OfficeToPdf(String officePath) {
  106. //G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docx
  107. String[] split = officePath.split("⌒");
  108. int lastIndex = split[0].lastIndexOf(".");
  109. int lastNameIndex = split[0].lastIndexOf("/");
  110. String officeType = split[0].substring(lastIndex+1);
  111. String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";
  112. String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";
  113. File file = new File(split[0]);
  114. File pdfFile = new File(OutPutPath+officeName);
  115. //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
  116. if(pdfFile.exists()){
  117. return OutPutPath+officeName;
  118. }
  119. if (file.exists()) {
  120. double bytes = file.length();
  121. double kilobytes = (bytes / 1024);
  122. double megabytes = (kilobytes / 1024);
  123. DecimalFormat df = new DecimalFormat("0.00");
  124. df.setRoundingMode(RoundingMode.HALF_UP);
  125. String MB = df.format(megabytes);
  126. Double Size = Double.parseDouble(MB);
  127. if(Size>10){
  128. return Size+"MB";
  129. }
  130. //"doc", "docx", "xls","xlsx", "ppt", "pptx"
  131. try {
  132. if(officeType.equals("doc")||officeType.equals("docx")){
  133. Word2Pdf(split[0],OutPutPath,officeName);
  134. }else if(officeType.equals("xls")||officeType.equals("xlsx")){
  135. Excel2Pdf(split[0],OutPutPath,officeName);
  136. }else if(officeType.equals("ppt")||officeType.equals("pptx")){
  137. PPT2Pdf(split[0],OutPutPath,officeName);
  138. }else{
  139. Sysout.println("无法识别该文件!");
  140. return "Error";
  141. }
  142. } catch (Exception e) {
  143. e.printStackTrace();
  144. }
  145. } else {
  146. return "NotExists";
  147. }
  148. return OutPutPath+officeName;
  149. }
  150. }

license.xml

  1. <License>
  2. <Data>
  3. <Products>
  4. <Product>Aspose.Total for Java</Product>
  5. <Product>Aspose.Words for Java</Product>
  6. </Products>
  7. <EditionType>Enterprise</EditionType>
  8. <SubscriptionExpiry>20991231</SubscriptionExpiry>
  9. <LicenseExpiry>20991231</LicenseExpiry>
  10. <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  11. </Data>
  12. <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
  13. </Signature>
  14. </License>

优点

使用aspose的优点就是转换快,可以跨平台,需要注意的就是中英文乱码,如果出现乱码,大家直接百度搜索aspose转换中文乱码即可,教程简单无脑,直接替换字体就行,无伤大雅。

如果是可以网上编辑的话

免费方案:
①采用dsoframer。dsoframer是微软提供一款开源的用于在线编辑、调用Word、 Excel 、PowerPoint等的ActiveX控件。缺点:只支持IE浏览器,由于dsoframer是早些年发布的,一直都没有更新,可能ie10、ie11下运行会有问题;调用起来比较复杂,功能少;客户端插件安装不方便,比如会遇到浏览器阻拦不能成功安装,甚至不提示安装等问题。
②利用Office Online 实现文档在线预览
利用office online 平台进行office 文档的在线查看,主旨在于获取文档的具体地址,通过Office 平台提供的链接地址指向需要预览的文档地址即可,例:http://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2fvideo.ch9.ms%2fbuild%2f2011%2fslides%2fTOOL-532T\_Sutter.pptx
这个链接分为了两部分,一部分是 http://view.officeapps.live.com/op/view.aspx?src=,后面那个是具体的文档地址,用URLEncode进行处理的链接地址

通过拼接的地址即可实现office 的在线预览
需要注意的是:office 在线预览限制

文档访问地址不能直接使用 ip,需要通过域名访问,并且端口必须是 80 端口
文档的格式(必须为以下格式之一):
Word:docx、docm、dotm、dotx
Excel:xlsx、xlsb、xls、xlsm
PowerPoint:pptx、ppsx、ppt、pps、pptm、potm、ppam、potx、ppsm
文档的大小:Word 和 PowerPoint 文档必须小于 10 兆字节;Excel 必须小于五兆字节(通过office web app 部署的本地服务器可以设置文档大小)
③将上传的docx和doc格式的Word文档进行解析,解析成html格式、或者使用前端编辑器tinymce直接预览内容(推荐)
两个方案:
1、我们可以在自己Word预览按钮上加个预览事件,这个Word文档肯定是上传到我们服务器上的,点击的时候,我们后台获取到这个Word的地址,然后使用java解析一下这个Word,然后把内容传递到前台,我们使用tinymce的setContent将Word解析的html内容导入到编辑器中,然后将编辑器设为只读(需要用到tinymce编辑器)。
2、我们把Word转换为html,将html生成到服务器上,在事件中返回html的路径,进行一个location或者其他处理,来进行Word的预览。
以上两个方案的缺点就是不能百分比做到格式统一,但是可以做到百分之80以上的格式+图片的预览。

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读

    相关 图片在线功能实现过程

    另外一个同事开发出来一个鼠标移动上去就显示图片的功能,但是总是不好用,所以我就是用jquery按照他的思路写了一个,简单的显示是实现了的,但是在弹出框的内部计算边框范围是有难度