• 用JAVA如何实现word文档在线预览


    1.思路,利用FTL(freemarker)生成word文档

    2.利用免费工具aspose将word转换PDF

    3使用PDF.JS在线预览。

    第一步比较多,就不一一代码。本次主要讲2,3步

    源码如下:AsposeUtil.java,把word转换PDF,存放本地,

    1.需要JAR包

    百度网盘 请输入提取码 提取码: 630z

    2.配置POM.xml

    1. <dependency>
    2. <groupId>com.asposegroupId>
    3. <artifactId>aspose-wordsartifactId>
    4. <version>0.0.1-SNAPSHOTversion>
    5. <scope>systemscope>
    6. <systemPath>${project.basedir}/outlib/aspose-words-16.8.0-jdk16.jarsystemPath>
    7. dependency>
    8. <dependency>
    9. <groupId>com.asposegroupId>
    10. <artifactId>aspose-cellsartifactId>
    11. <version>0.0.1-SNAPSHOTversion>
    12. <scope>systemscope>
    13. <systemPath>${project.basedir}/outlib/aspose-cells-8.5.2(1).jarsystemPath>
    14. dependency>
    15. <dependency>
    16. <groupId>com.asposegroupId>
    17. <artifactId>aspose-slidesartifactId>
    18. <version>0.0.1-SNAPSHOTversion>
    19. <scope>systemscope>
    20. <systemPath>${project.basedir}/outlib/aspose.slides-15.9.0.jarsystemPath>
    21. dependency>
    22. <dependency>
    23. <groupId>cn.hutoolgroupId>
    24. <artifactId>hutool-coreartifactId>
    25. <version>5.6.5version>
    26. dependency>

     3.配置,防止乱码, license.xml代码内容

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

    4.WORD转PDF源码:

    1. package com.bootdo.common.utils;
    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.aspose.words.SaveFormat;
    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) {//excel
    24. com.aspose.cells.License aposeLic = new com.aspose.cells.License();
    25. aposeLic.setLicense(is);
    26. result = true;
    27. } else if (type == 2) {//word
    28. com.aspose.words.License aposeLic = new com.aspose.words.License();
    29. aposeLic.setLicense(is);
    30. result = true;
    31. } else {//ppt
    32. com.aspose.slides.License aposeLic = new com.aspose.slides.License();
    33. aposeLic.setLicense(is);
    34. result = true;
    35. }
    36. } catch (Exception e) {
    37. e.printStackTrace();
    38. }
    39. return result;
    40. }
    41. public static void Excel2Pdf(String officePath,String OutPutPath,String officeName) {
    42. // 验证License
    43. if (!getLicense(1)) {
    44. return;
    45. }
    46. try {
    47. File file = new File(OutPutPath);
    48. if (!file.exists()) {
    49. file.mkdirs();
    50. }
    51. // long old = Sysout.currentTimeMillis();
    52. Workbook wb = new Workbook(officePath);// 原始excel路径
    53. File pdfFile = new File(OutPutPath+officeName);// 输出路径
    54. FileOutputStream fileOS = new FileOutputStream(pdfFile);
    55. //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
    56. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
    57. pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
    58. wb.save(fileOS, pdfSaveOptions);
    59. // long now = Sysout.currentTimeMillis();
    60. // Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");
    61. } catch (Exception e) {
    62. e.printStackTrace();
    63. }
    64. }
    65. public static void main(String[] args) throws Exception {
    66. AsposeUtil bean = new AsposeUtil();
    67. // bean.word2Pdf2("D:\\pdf\\12.docx","D:\\pdf\\12.pdf");
    68. bean.word2Pdf2("C:\\wordTemple\\han.docx","C:\\wordTemple\\1234.pdf");
    69. }
    70. public void word2Pdf2(String inpath,String outpath) throws Exception {
    71. if (!getLicense(2)) {
    72. System.out.println("非法------------");
    73. return;
    74. }
    75. long old = System.currentTimeMillis();
    76. File file = new File(outpath);
    77. FileOutputStream os = new FileOutputStream(file);
    78. //解决乱码
    79. //如果是windows执行,不需要加这个
    80. //TODO 如果是linux执行,需要添加这个*****
    81. //FontSettings.setFontsFolder("/usr/share/fonts",true);
    82. Document doc = new Document(inpath);
    83. //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
    84. doc.save(os, SaveFormat.PDF);
    85. long now = System.currentTimeMillis();
    86. System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
    87. }
    88. public static void Word2Pdf(String officePath,String OutPutPath,String officeName) {
    89. // 验证License
    90. if (!getLicense(2)) {
    91. return;
    92. }
    93. try {
    94. File file = new File(OutPutPath);
    95. if (!file.exists()) {
    96. file.mkdirs();
    97. }
    98. Document doc = new Document(officePath);// 原始word路径
    99. File pdfFile = new File(OutPutPath+officeName);// 输出路径
    100. FileOutputStream fileOS = new FileOutputStream(pdfFile);
    101. doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
    102. } catch (Exception e) {
    103. e.printStackTrace();
    104. }
    105. }
    106. public static void PPT2Pdf(String officePath,String OutPutPath,String officeName) {
    107. // 验证License
    108. if (!getLicense(3)) {
    109. return;
    110. }
    111. try {
    112. File PathFile = new File(OutPutPath);
    113. if (!PathFile.exists()) {
    114. PathFile.mkdirs();
    115. }
    116. InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径
    117. Presentation pres = new Presentation(slides);
    118. File file = new File(OutPutPath+officeName);// 输出pdf路径
    119. FileOutputStream fileOS = new FileOutputStream(file);
    120. pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
    121. } catch (Exception e) {
    122. e.printStackTrace();
    123. }
    124. }
    125. public static String OfficeToPdf(String officePath) {
    126. //G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docx
    127. String[] split = officePath.split("⌒");
    128. int lastIndex = split[0].lastIndexOf(".");
    129. int lastNameIndex = split[0].lastIndexOf("/");
    130. String officeType = split[0].substring(lastIndex+1);
    131. String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";
    132. String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";
    133. File file = new File(split[0]);
    134. File pdfFile = new File(OutPutPath+officeName);
    135. //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
    136. if(pdfFile.exists()){
    137. return OutPutPath+officeName;
    138. }
    139. if (file.exists()) {
    140. double bytes = file.length();
    141. double kilobytes = (bytes / 1024);
    142. double megabytes = (kilobytes / 1024);
    143. DecimalFormat df = new DecimalFormat("0.00");
    144. df.setRoundingMode(RoundingMode.HALF_UP);
    145. String MB = df.format(megabytes);
    146. Double Size = Double.parseDouble(MB);
    147. if(Size>10){
    148. return Size+"MB";
    149. }
    150. //"doc", "docx", "xls","xlsx", "ppt", "pptx"
    151. try {
    152. if(officeType.equals("doc")||officeType.equals("docx")){
    153. Word2Pdf(split[0],OutPutPath,officeName);
    154. }else if(officeType.equals("xls")||officeType.equals("xlsx")){
    155. Excel2Pdf(split[0],OutPutPath,officeName);
    156. }else if(officeType.equals("ppt")||officeType.equals("pptx")){
    157. PPT2Pdf(split[0],OutPutPath,officeName);
    158. }else{
    159. System.out.println("无法识别该文件!");
    160. return "Error";
    161. }
    162. } catch (Exception e) {
    163. e.printStackTrace();
    164. }
    165. } else {
    166. return "NotExists";
    167. }
    168. return OutPutPath+officeName;
    169. }
    170. }

          第二步就完成了,接下来下载PDF.js  

    1. pdf.js文件 下载后放入到项目静态文件夹(下载地址:PDF.js
    2. 可运行的springboot项目

    首先为了直观的展示,springboot直接返回一个写死文件路径的输出流

    前端获取展示

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>pdf预览title>
    6. head>
    7. <body>
    8. <h1 onclick="onLineReadPDF()" style="cursor: pointer;color:blue">在线阅读PDF文件h1>
    9. <script>
    10. function onLineReadPDF() {
    11. var id=$("#id").val();
    12. var addPage =layer.open({
    13. type : 2,
    14. title : '预览',
    15. maxmin : true,
    16. shadeClose : false, // 点击遮罩关闭层
    17. area : [ '600px', '460px' ],
    18. content : '/mypdf/web/viewer.html?file=/xiewai/api/file/onlinePreview/'+id
    19. //content : prefix + '/api/file/onlinePreview/'+id // iframe的url
    20. });
    21. layer.full(addPage);
    22. }
    23. script>
    24. body>
    25. html>

     /mypdf/web/viewer.html是下载的PDF文件包(放在static文件路径下),后面的路径是接口的方法,可通过传id等参数查询生成word

    我的方法是:

    1. //生成采集文件文档
    2. @GetMapping("/api/file/onlinePreview/{id}")
    3. void onlinePreview(@PathVariable("id") String id, HttpServletResponse response, HttpServletRequest request,HttpSession session,Model model) throws Exception{
    4. //生成word文档
    5. Random rd=new Random();
    6. String url="docs/xiewai.docx";
    7. HashMap parm=new HashMap();
    8. parm.put("id", id);
    9. List list=warningRecordService.listXiewai(parm);
    10. DocumentHandler dh=new DocumentHandler();
    11. response.setContentType("text/html;charset=utf-8");
    12. request.setCharacterEncoding("UTF-8");
    13. String filename = dh.createTaskReportDoc(list,id);
    14. model.addAttribute("filename",tem+"files/"+filename);
    15. AsposeUtil bean = new AsposeUtil();
    16. // bean.word2Pdf2("D:\\pdf\\12.docx","D:\\pdf\\12.pdf");
    17. String inpath=loadAddress+"\\"+filename;
    18. String curr="X"+System.currentTimeMillis()+rd.nextInt(1000);
    19. String outPath=loadAddress+"\\"+curr+".pdf";
    20. bean.word2Pdf2(inpath,outPath);
    21. File f = new File(outPath);
    22. if (f.exists()) {
    23. byte[] data = null;
    24. FileInputStream input=null;
    25. try {
    26. input= new FileInputStream(f);
    27. data = new byte[input.available()];
    28. input.read(data);
    29. response.getOutputStream().write(data);
    30. } catch (Exception e) {
    31. System.out.println("pdf文件处理异常:" + e);
    32. }finally{
    33. try {
    34. if(input!=null){
    35. input.close();
    36. }
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. }
    42. }

    这样就可以在线预览了

    另外附上生成word 表格的代码,填充word的数据

    1. public String createHanReportDoc(List list,String id,String showname) throws Exception {
    2. // 创建数据
    3. //Map dataMap = new HashMap();
    4. //dataMap =getTaskReportData(dataMap, list);
    5. XieWaiDO dataMap = new XieWaiDO();
    6. dataMap =list.get(0);
    7. // 获取模板
    8. String mjinfoJson=dataMap.getXwMjInfo();
    9. StringBuffer sb=new StringBuffer();
    10. List mjInfo = new ArrayList();
    11. if(mjinfoJson!=null&&!mjinfoJson.equals("")){
    12. JSONArray json=JSONArray.parseArray(mjinfoJson);
    13. if(json.size()>0){
    14. for(int i=0;i
    15. Map map = new HashMap();
    16. JSONObject job =json.getJSONObject(i); //
    17. String name=(String) job.get("name");
    18. if(i!=0&&i!=job.size()-1){
    19. sb.append("、");
    20. }
    21. sb.append(name);
    22. }
    23. }
    24. dataMap.setXwMjInfo(sb.toString());
    25. }
    26. Date now=new Date();
    27. String nowDate=sdf2.format(now);
    28. dataMap.setReceiveTime(nowDate);
    29. dataMap.setRemarks(showname);
    30. Configuration configuration = new Configuration();
    31. configuration.setDefaultEncoding("utf-8");
    32. configuration.setDirectoryForTemplateLoading(new File(loadAddress));
    33. System.out.println(this.getClass().getResource(""));
    34. Template t = null;
    35. String tem=sdf3.format(new Date());
    36. String tt=id+""+tem;
    37. String name = "\\han_"+tt+".docx";
    38. String ftl="han.ftl";
    39. File file = new File(loadAddress + name);
    40. try {
    41. t = configuration.getTemplate(ftl);
    42. t.setEncoding("UTF-8");
    43. Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(loadAddress + name), "UTF-8"));
    44. t.process(dataMap, out);
    45. out.close();
    46. } catch (IOException e) {
    47. e.printStackTrace();
    48. } catch (TemplateException e) {
    49. e.printStackTrace();
    50. }
    51. return name;
    52. }

  • 相关阅读:
    zabbix集群搭建分布式监控的操作步骤
    global关键字、python实现ATM简单功能
    HTX 与 Zebec Protocol 展开深度合作,并将以质押者的身份参与 ZBC Staking
    微信公众号之底部菜单
    基于脑电信号的癫痫发作预测
    leetcode 3.11
    【Python-pyecharts】全国数据分析岗招聘信息可视化
    leetcode经典面试150题---1.合并两个有序数组
    java计算机毕业设计网络教学系统源码+系统+数据库+lw文档
    scrollIntoView() 方法的使用
  • 原文地址:https://blog.csdn.net/chenqqabcdchenqqabcd/article/details/127651555