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

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

3使用PDF.JS在线预览。

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

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

1.需要JAR包

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

2.配置POM.xml

<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>0.0.1-SNAPSHOT</version><scope>system</scope><systemPath>${project.basedir}/outlib/aspose-words-16.8.0-jdk16.jar</systemPath></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>0.0.1-SNAPSHOT</version><scope>system</scope><systemPath>${project.basedir}/outlib/aspose-cells-8.5.2(1).jar</systemPath></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-slides</artifactId><version>0.0.1-SNAPSHOT</version><scope>system</scope><systemPath>${project.basedir}/outlib/aspose.slides-15.9.0.jar</systemPath></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId><version>5.6.5</version></dependency>

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

<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

4.WORD转PDF源码:

package com.bootdo.common.utils;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;public class AsposeUtil {/*** 获取license** @return*/public static boolean getLicense(int type) {boolean result = false;try {InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");if (type == 1) {//excelcom.aspose.cells.License aposeLic = new com.aspose.cells.License();aposeLic.setLicense(is);result = true;} else if (type == 2) {//wordcom.aspose.words.License aposeLic = new com.aspose.words.License();aposeLic.setLicense(is);result = true;} else {//pptcom.aspose.slides.License aposeLic = new com.aspose.slides.License();aposeLic.setLicense(is);result = true;}} catch (Exception e) {e.printStackTrace();}return result;}public static void Excel2Pdf(String officePath,String OutPutPath,String officeName) {// 验证Licenseif (!getLicense(1)) {return;}try {File file = new File(OutPutPath);if (!file.exists()) {file.mkdirs();}
//            long old = Sysout.currentTimeMillis();Workbook wb = new Workbook(officePath);// 原始excel路径File pdfFile = new File(OutPutPath+officeName);// 输出路径FileOutputStream fileOS = new FileOutputStream(pdfFile);//wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);wb.save(fileOS, pdfSaveOptions);
//            long now = Sysout.currentTimeMillis();
//            Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) throws Exception {AsposeUtil bean = new AsposeUtil();
//        bean.word2Pdf2("D:\\pdf\\12.docx","D:\\pdf\\12.pdf");bean.word2Pdf2("C:\\wordTemple\\han.docx","C:\\wordTemple\\1234.pdf");}public  void word2Pdf2(String inpath,String outpath) throws Exception {if (!getLicense(2)) {System.out.println("非法------------");return;}long old = System.currentTimeMillis();File file = new File(outpath);FileOutputStream os = new FileOutputStream(file);//解决乱码//如果是windows执行,不需要加这个//TODO 如果是linux执行,需要添加这个*****//FontSettings.setFontsFolder("/usr/share/fonts",true);Document doc = new Document(inpath);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换doc.save(os, SaveFormat.PDF);long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");}public static void Word2Pdf(String officePath,String OutPutPath,String officeName) {// 验证Licenseif (!getLicense(2)) {return;}try {File file = new File(OutPutPath);if (!file.exists()) {file.mkdirs();}Document doc = new Document(officePath);// 原始word路径File pdfFile = new File(OutPutPath+officeName);// 输出路径FileOutputStream fileOS = new FileOutputStream(pdfFile);doc.save(fileOS, com.aspose.words.SaveFormat.PDF);} catch (Exception e) {e.printStackTrace();}}public static void PPT2Pdf(String officePath,String OutPutPath,String officeName) {// 验证Licenseif (!getLicense(3)) {return;}try {File PathFile = new File(OutPutPath);if (!PathFile.exists()) {PathFile.mkdirs();}InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径Presentation pres = new Presentation(slides);File file = new File(OutPutPath+officeName);// 输出pdf路径FileOutputStream fileOS = new FileOutputStream(file);pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);} catch (Exception e) {e.printStackTrace();}}public static String OfficeToPdf(String officePath) {//G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docxString[] split = officePath.split("⌒");int lastIndex = split[0].lastIndexOf(".");int lastNameIndex = split[0].lastIndexOf("/");String officeType = split[0].substring(lastIndex+1);String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";File file = new File(split[0]);File pdfFile = new File(OutPutPath+officeName);//判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。if(pdfFile.exists()){return OutPutPath+officeName;}if (file.exists()) {double bytes = file.length();double kilobytes = (bytes / 1024);double megabytes = (kilobytes / 1024);DecimalFormat df = new DecimalFormat("0.00");df.setRoundingMode(RoundingMode.HALF_UP);String MB = df.format(megabytes);Double Size = Double.parseDouble(MB);if(Size>10){return Size+"MB";}//"doc", "docx", "xls","xlsx", "ppt", "pptx"try {if(officeType.equals("doc")||officeType.equals("docx")){Word2Pdf(split[0],OutPutPath,officeName);}else if(officeType.equals("xls")||officeType.equals("xlsx")){Excel2Pdf(split[0],OutPutPath,officeName);}else if(officeType.equals("ppt")||officeType.equals("pptx")){PPT2Pdf(split[0],OutPutPath,officeName);}else{System.out.println("无法识别该文件!");return "Error";}} catch (Exception e) {e.printStackTrace();}} else {return "NotExists";}return OutPutPath+officeName;}}

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

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

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

前端获取展示

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>pdf预览</title>
</head>
<body>
<h1 onclick="onLineReadPDF()" style="cursor: pointer;color:blue">在线阅读PDF文件</h1><script>function onLineReadPDF() {var id=$("#id").val();var addPage =layer.open({type : 2,title : '预览',maxmin : true,shadeClose : false, // 点击遮罩关闭层area : [ '600px', '460px' ],content : '/mypdf/web/viewer.html?file=/xiewai/api/file/onlinePreview/'+id //content : prefix + '/api/file/onlinePreview/'+id // iframe的url});layer.full(addPage);}
</script>
</body>
</html>

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

我的方法是:

//生成采集文件文档@GetMapping("/api/file/onlinePreview/{id}")void   onlinePreview(@PathVariable("id") String id, HttpServletResponse response, HttpServletRequest request,HttpSession session,Model model) throws Exception{//生成word文档Random rd=new Random();String url="docs/xiewai.docx";HashMap<String, Object> parm=new HashMap<String, Object>();parm.put("id", id);List<XieWaiDO>  list=warningRecordService.listXiewai(parm);DocumentHandler dh=new DocumentHandler();response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("UTF-8");String filename = dh.createTaskReportDoc(list,id);model.addAttribute("filename",tem+"files/"+filename);AsposeUtil bean = new AsposeUtil();
//      bean.word2Pdf2("D:\\pdf\\12.docx","D:\\pdf\\12.pdf");String inpath=loadAddress+"\\"+filename;String curr="X"+System.currentTimeMillis()+rd.nextInt(1000);String outPath=loadAddress+"\\"+curr+".pdf";bean.word2Pdf2(inpath,outPath);  File f = new File(outPath);if (f.exists()) {byte[] data = null;FileInputStream input=null;try {input= new FileInputStream(f);data = new byte[input.available()];input.read(data);response.getOutputStream().write(data);} catch (Exception e) {System.out.println("pdf文件处理异常:" + e);}finally{try {if(input!=null){input.close();}} catch (IOException e) {e.printStackTrace();}}}}

这样就可以在线预览了

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

public String createHanReportDoc(List<XieWaiDO> list,String id,String showname) throws Exception {// 创建数据//Map<String, Object> dataMap = new HashMap<String, Object>();//dataMap =getTaskReportData(dataMap, list);XieWaiDO dataMap = new XieWaiDO();dataMap =list.get(0);   // 获取模板String mjinfoJson=dataMap.getXwMjInfo();StringBuffer sb=new StringBuffer();List mjInfo = new ArrayList();if(mjinfoJson!=null&&!mjinfoJson.equals("")){JSONArray json=JSONArray.parseArray(mjinfoJson);if(json.size()>0){for(int i=0;i<json.size();i++){Map map = new HashMap();JSONObject job =json.getJSONObject(i);  //String name=(String) job.get("name");if(i!=0&&i!=job.size()-1){sb.append("、");}sb.append(name);}}dataMap.setXwMjInfo(sb.toString());}Date now=new Date();String nowDate=sdf2.format(now);dataMap.setReceiveTime(nowDate);dataMap.setRemarks(showname);Configuration configuration = new Configuration();configuration.setDefaultEncoding("utf-8");configuration.setDirectoryForTemplateLoading(new File(loadAddress));System.out.println(this.getClass().getResource(""));Template t = null;String tem=sdf3.format(new Date());String tt=id+""+tem;String name = "\\han_"+tt+".docx";String ftl="han.ftl";File file = new File(loadAddress + name);try {t = configuration.getTemplate(ftl);t.setEncoding("UTF-8");Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(loadAddress + name), "UTF-8"));t.process(dataMap, out);out.close();} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}return name;}

用JAVA如何实现word文档在线预览相关推荐

  1. 利用OpenOffice实现word文档在线预览

    项目中遇到的word文档在线预览需求,查阅很多资料决定利用openoffice转换word文档为pdf/html进行预览实现. 1.下载openoffice4安装 www.openoffice.org ...

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

    预览Word.PPT.Excel 我之前发过一篇文章,是介绍office预览和编辑的但是大部门插件都是收费的,我这次提供的是免费的一个将Word.PPT.Excel转换为PDF然后在浏览器进行预览,之 ...

  3. java flexpaper_Java+FlexPaper+swfTools 文档在线预览demo

    1.概述 主要原理 1.通过第三方工具openoffice,将word.excel.ppt.txt等文件转换为pdf文件 2.通过swfTools将pdf文件转换成swf格式的文件 3.通过FlexP ...

  4. word文档在线预览

    移动互联网的到来,使得Word文档在移动端的显示成了问题.大家解决方法大概有三种:转换为PDF.用HTML模拟页面效果.纯网页效果. 1.使用微软的在线预览功能,更适合pc端 'https://vie ...

  5. office文档在线预览工具平台选型

    ​​​​​​在线预览原理 文档在线预览说明: 1.业务系统生成文档浏览地址,用户通过终端进行访 2.用户终端访问文档预览资源地址,请求文档解析器,解析器分为私有云和公有云部署,作用是将文档进行解析成x ...

  6. 用JAVA如何实现word文档在线编辑预览的功能?

    免费方案: ①采用dsoframer. dsoframer是微软提供一款开源的用于在线编辑.调用Word. Excel .PowerPoint等的ActiveX控件.缺点:只支持IE浏览器,由于dso ...

  7. 前端【vue】实现文档在线预览功能,在线预览pdf、word、xls、ppt等office文件

    前端江太公 前端实现文档在线预览功能 最直接的就是使用XDOC 文档云服务 XDOC可以实现预览以DataURI表示的DOC文档,此外XDOC还可以实现文本.带参数文本.html文本.json文本.公 ...

  8. 文档在线预览(二)word、pdf、excel文件转html以实现文档在线预览

    文章目录 一.前言 1.aspose 2 .poi + pdfbox 3 spire 二.将文件转换成html字符串 1.将word文件转成html字符串 1.1 使用aspose 1.2 使用poi ...

  9. Java如何实现文档在线预览

    文章目录 一.概述 二.Java实现文档在线预览 2.1 永中DCS简介 2.2 使用方式 2.3 centos安装部署DCS服务 编辑Java环境 安装部署Tomcat 部署DCS工程 安装ngin ...

最新文章

  1. php laravel用的多不,php-Laravel多个可选参数不起作用
  2. K-L散度(相对熵)
  3. Sencha Touch 动态修改store的url
  4. S3C2440时钟体系结构
  5. 反序列化层遍历二叉树
  6. jug java_架构大型企业Java项目–我的虚拟JUG会话
  7. 二手机Q1行情报告:iPhone 11、华为Mate、P40(5G)等小幅涨价
  8. 构建大型 Mobx 应用的几个建议
  9. 如何正视自己的劣势?面试!
  10. php 页面字体大小,CSS_做网页字体大小参考 网页中同字号字体的不同单位对比列表,对于WEB前端页面开发,字体大 - phpStudy...
  11. Linux下载源码编译出错,编译小度wifi源码出错!
  12. 微信小程序网络请求api中HTML格式问题
  13. 如何改typecho主题头像_一个比较免费又漂亮的typecho主题-Akina for Typecho
  14. 梦江湖获取服务器信息,《一梦江湖》6月5日更新公告
  15. 【最新】Firefox Manifest V3:进展及下一步计划
  16. php 7.0 nts,PHP最新版本7.0.1-nts-Win32-VC14-x86
  17. SPI 读取不同长度 寄存器_敏矽微电子Cortex-M0学习笔记10-SPI通信详解
  18. 干货丨浅谈足式机器人的运动控制
  19. toad for mysql 彻底卸载_toad for mysql 下载
  20. c语言编程单向,C语言单向链表的表示与实现实例详解

热门文章

  1. PCM音频数据封装为WAV文件
  2. HTML中的乱码问题
  3. PHP科大讯飞翻译API接口接入
  4. multiset学习之修改操作clear,erase,swap,extract,merge
  5. 一个英文单词译义背后的利益
  6. 关于USB的那点糗事
  7. 子网划分(内含算法详解)
  8. python 列表转为字典的两个小方
  9. 什么是深拷贝,什么是浅拷贝
  10. 计算机设备打开,Win7如何快速打开设备管理器?