aspose实现word,excel在线预览

一,项目中引入aspose依赖

     <dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>15.8.0</version></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>8.5.2</version></dependency>

建议将jar包下载下来并上传到自己公司的私服里
网盘地址:
链接:https://pan.baidu.com/s/1UoqK3ru_Xpa3LbE3DOn6kA
提取码:0ihv

二:把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>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber></Data><Signature>0nRuwNEddXwLfXB7pw66G71MS93gW8mNzJ7vuh3Sf4VAEOBfpxtHLCotymv1PoeukxYe31K441Ivq0Pkvx1yZZG4O1KCv3Omdbs7uqzUB4xXHlOub4VsTODzDJ5MWHqlRCB1HHcGjlyT2sVGiovLt0Grvqw5+QXBuinoBY0suX0=</Signature>
</License>

word,excel转pdf可共用一个license.xml

三.封装工具类

import com.alibaba.excel.EasyExcel;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;@Slf4j
@Component
public class FileUtil {/*** 文件下载方法** @param filename 文件保存名* @param filePath 文件下载路径* @param res* @throws IOException*/public static void downloadFile(String filename, String filePath, HttpServletResponse res) throws IOException {// 发送给客户端的数据OutputStream outputStream = res.getOutputStream();byte[] buff = new byte[1024];BufferedInputStream bis = null;// 读取filenamebis = new BufferedInputStream(new FileInputStream(new File(filePath + filename)));int i = bis.read(buff);while (i != -1) {outputStream.write(buff, 0, buff.length);outputStream.flush();i = bis.read(buff);}outputStream.close();}public static void deleteFile(String filename, String filePath) {File file = new File(filePath + filename);if (file.exists()) {//文件是否存在file.delete();//删除文件}}/*** @Author WXK* @Description 返回预览pdf流* @Date 2021/3/11**/public static void previewFile1(String filePath, HttpServletResponse res) throws IOException {// 发送给客户端的数据OutputStream outputStream = res.getOutputStream();try {byte[] buff = new byte[1024];BufferedInputStream bis = null;// 读取filenamebis = new BufferedInputStream(new FileInputStream(new File(filePath)));int i = bis.read(buff);while (i != -1) {outputStream.write(buff, 0, buff.length);outputStream.flush();i = bis.read(buff);}} catch (Exception e) {e.printStackTrace();} finally {outputStream.close();}}/*** @Author WXK* @Description 删除转换生成的pdf文件* @Date 2021/3/11**/public static void deleteFile1(String filePath) {File file = new File(filePath);if (file.exists()) {//文件是否存在file.delete();//删除文件}}public static boolean getLicense() {boolean result = false;try {InputStream is = Test.class.getClassLoader().getResourceAsStream("license.xml"); //  License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static boolean getExcelLicense() {boolean result = false;try {InputStream is = Test.class.getClassLoader().getResourceAsStream("license.xml"); //  com.aspose.cells.License license = new com.aspose.cells.License();license.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** @Author WXK* @Description word转 pdf* @Date 2021/3/12**/public static String doc2pdf(String fileName, String filePath) {if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return null;}try {String oldFile = filePath + fileName;String newFile = oldFile.substring(0, oldFile.lastIndexOf("."))+".pdf";File file = new File(newFile);  //新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(oldFile);                    //Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换log.info("转换成功");  //转化用时return newFile;} catch (Exception e) {e.printStackTrace();}return null;}/*** @Author WXK* @Description 上传文件时,word转pdf 保存在本地* @Date 2021/3/29  **/public static String doc2pdf(InputStream inputStream,String fileName, String filePath) {if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return null;}try {String newFile = filePath + fileName;File file = new File(newFile);  //新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(inputStream);                    //Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换log.info("转换成功");  //转化用时return newFile;} catch (Exception e) {e.printStackTrace();}return null;}/*** @Author WXK* @Description excel转pdf* @Date 2021/3/22**/public static String excelToPdf(String fileName, String filePath) throws IOException{if (!getExcelLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return null;}FileOutputStream fileOS=null;try {String oldFile = filePath + fileName;String newFile = oldFile.substring(0, oldFile.lastIndexOf("."))+".pdf";File pdfFile = new File(newFile);// 输出路径/* Workbook wb = new Workbook(oldFile);// 原始excel路径fileOS = new FileOutputStream(pdfFile);wb.save(fileOS, SaveFormat.PDF);fileOS.flush();log.info("转换成功");*/Workbook wb = new Workbook(oldFile);// 原始excel路径fileOS = new FileOutputStream(newFile);PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();pdfSaveOptions.setOnePagePerSheet(true);int[] autoDrawSheets={3};//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。autoDraw(wb,autoDrawSheets);int[] showSheets={0};//隐藏workbook中不需要的sheet页。printSheetPage(wb,showSheets);wb.save(fileOS, pdfSaveOptions);fileOS.flush();fileOS.close();log.info("完毕");return newFile;} catch (Exception e) {e.printStackTrace();}finally {fileOS.close();}return null;}/*** @Author WXK* @Description 上传文件时 excel转pdf保存在本地* @Date 2021/3/29  **/public static String excelToPdf(InputStream inputStream, String fileName,String filePath) throws IOException{if (!getExcelLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return null;}FileOutputStream fileOS=null;try {String newFile = filePath + fileName;Workbook wb = new Workbook(inputStream);// 原始excel路径fileOS = new FileOutputStream(newFile);PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();pdfSaveOptions.setOnePagePerSheet(true);int[] autoDrawSheets={3};//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。autoDraw(wb,autoDrawSheets);int[] showSheets={0};//隐藏workbook中不需要的sheet页。printSheetPage(wb,showSheets);wb.save(fileOS, pdfSaveOptions);fileOS.flush();fileOS.close();log.info("完毕");return newFile;} catch (Exception e) {e.printStackTrace();}finally {fileOS.close();}return null;}/*** 设置打印的sheet 自动拉伸比例* @param wb* @param page 自动拉伸的页的sheet数组*/public static void autoDraw(Workbook wb,int[] page){if(null!=page&&page.length>0){for (int i = 0; i < page.length; i++) {wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();wb.getWorksheets().get(i).getVerticalPageBreaks().clear();}}}/*** 隐藏workbook中不需要的sheet页。* @param wb* @param page 显示页的sheet数组*/public static void printSheetPage(Workbook wb,int[] page){for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {wb.getWorksheets().get(i).setVisible(false);}if(null==page||page.length==0){wb.getWorksheets().get(0).setVisible(true);}else{for (int i = 0; i < page.length; i++) {wb.getWorksheets().get(i).setVisible(true);}}}/*** @Author WXK* @Description 查看对应的.pdf文件是否存在* @Date 2021/3/12**/public static boolean checkFileExist(String filePath) {File file = new File(filePath);if (file.exists()) {//文件是否存在return true;}return false;}
}

四:controller类

import com.shuangjia.constant.Constant;
import com.shuangjia.model.PeDownloadLog;
import com.shuangjia.model.PeFile;
import com.shuangjia.model.ResultEntity;
import com.shuangjia.model.UserSession;
import com.shuangjia.util.FileUtil;
import com.shuangjia.web.pepd.feginService.PeFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
public class PeFileController {@Value("${upload.path}")private  String path;@Value("${upload.picture.path}")private  String uploadPath;@PostMapping("/previewFile")@ApiOperation("返回文件流")public void previewFile(@RequestBody PeFile po,HttpServletResponse response)throws IOException{String fileName=po.getFileName();String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);if("pdf".equalsIgnoreCase(suffix)){String type = new MimetypesFileTypeMap().getContentType(fileName);response.setHeader("Content-type",type);String newFileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");// 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);FileUtil.downloadFile(fileName,path,response);}String filePath = path + fileName.substring(0,fileName.lastIndexOf(".")) + ".pdf";if( FileUtil.checkFileExist(filePath)){FileUtil.previewFile1(filePath,response);}else {String newFilePath=null;if("XLSX".equalsIgnoreCase(suffix) || "XLS".equalsIgnoreCase(suffix)){newFilePath=FileUtil.excelToPdf(fileName,path);}else {//DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWFnewFilePath = FileUtil.doc2pdf(fileName, path);}if(StringUtils.isNotBlank(newFilePath)){FileUtil.previewFile1(newFilePath,response);}}}}

返回给前端的是一个pdf文件流
五:效果图

aspose实现word,excel在线预览相关推荐

  1. 使用aspose方式使excel,ppt,word进行在线预览。(无水印)

    使用aspose方式使excel,ppt,word进行在线预览.(无水印) 1.首先,页面需要用jquery中window.open();打开一个新页面. window.open(../fileMan ...

  2. 前端-Excel在线预览

    前端-Excel在线预览 最近项目中有一个 Excel 预览的需求,就调研了一下 xls/xlsx.word.ppt 文件在线预览功能的实现 . 实现 xls/xlsx.word.ppt 在线预览功能 ...

  3. 图片、pdf、wrod和excel 在线预览

    自定义文件服务器 图片.pdf.wrod和excel 在线预览 场景介绍 准备工作 预览图片,pdf 预览word 预览excel 效果图 场景介绍 因公司项目中需要使用到文件交互,因此在网上找了一个 ...

  4. Vue+SpringBoot实现Excel在线预览功能(PS:添加样式比较费劲)

    ** 问题还原: ** 在做项目时,用户需要上传Excel模板,里面有对应的各种数据.我们拿到这个Excel后,定时的根据其中的数据去查对应的实时数据并进行计算,然后将实时数据和计算后的数据保存到Ex ...

  5. Python excel转成html页面 excel 在线预览

    Python excel转成html页面 excel 在线预览 因为这两天公司的项目要用到在浏览excel 所以就在做这个功能.一开始查了很多资料 都是各种不行,最后好不容易找到一些辅助资料 终于是今 ...

  6. js-xlsx vue导入excel在线预览

    js-xlsx vue导入excel在线预览 导入XLSX库 官方地址Github 安装 npm install xlsx --s 引入 import XLSX from 'xlsx' HTML &l ...

  7. pdf,word,ppt在线预览

    pdf,word,ppt在线预览 先展示下效果 pdf跟ppt的预览效果: word的预览效果 实现过程-只需一个iframe标签即可 详细介绍请看这里 <iframe src="ht ...

  8. 富文本生成word并在线预览(附源码)

    记录富文本内容生成word并在线预览碰到的问题,以及最终的解决方案. 一.需求 当前项目需要将页面富文本中的内容,生成word并在线预览. 二.解决方案1(未解决) 1. openoffice wor ...

  9. Java 实现word pdf在线预览

    Java 实现word pdf在线预览 最近项目有这个需求,查找了一些资料,在这整理一下. 首先,pdf的文件,浏览器本身支持预览,不需要做什么处理. controller: 简单说下思路:就是利用i ...

最新文章

  1. android代码关闭数据库,android – 我应该如何正确打开和关闭我的数据库
  2. 在矩池云中保存Conda环境
  3. c++中goto语句用法
  4. 数据平台建设的几种方案
  5. JVM 新生代,老年代,永久代
  6. 蛋糕是叫胚子还是坯子_这个生日蛋糕太适合手残党了,不会裱花也能做,学会再不买着吃了...
  7. 《高等代数学》(姚慕生),习题1.2:三阶行列式
  8. C语言求三角形斜边长
  9. 【POJ 3322】 Bloxorz I
  10. 转载:asm volatile GCC的内嵌汇编语法 ATT汇编语言语法
  11. Win10 NVIDIA Container占用CPU高的处理方法
  12. mysql association_mybatis 一对一与一对多collection和association的使用
  13. MySQL数据表插入数据及增加语句
  14. Docker入门的亿点点学习
  15. 从Nginx到Pandownload,程序员如何避免面向监狱编程
  16. 如何让administrator不出现在windows7系统登录界面
  17. 3.1 Web前端:实战电商页面1:静态布局
  18. 浅析深度学习与计算机视觉
  19. SparkSql On Hive
  20. RabbitMq死信队列介绍

热门文章

  1. 使用 OpenWhisk 自建 Serverless 服务
  2. 中国半导体要从点到面,存储器为何是最好下手点?
  3. 第7课:郭盛华课程_Linux系统的常用操作命令
  4. 中外法律文献查找下载常用数据库大盘点
  5. Flutter之基础Widget
  6. 光敏电阻5506主要参数_光敏电阻详细参数?
  7. 爱创课堂每日一题第五十六天-对前端界面工程师这个职位是怎么样理解的?它的前景会怎么样?...
  8. docker: error pulling image configuration
  9. AD20 PCB导出Gerber、拼板,华秋DFM一键拼板,同理支持其他PCB EDA软件的Gerber导入与拼板
  10. Java实现快递管理系统一(views)