office文件转pdf在线预览
一、工具类
package com.sby.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 java.util.Locale;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;/*** Created with IntelliJ IDEA.** @Author: cqwuliu* @Date: 2024/02/08/11:41 will_isme@163.com* @Description:*/
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 String Excel2Pdf(String officePath,String OutPutPath,String officeName) {// 验证Licenseif (!getLicense(1)) {return null;}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);return pdfFile.getAbsolutePath();
// long now = Sysout.currentTimeMillis();
// Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");} catch (Exception e) {e.printStackTrace();System.err.println("Excel2Pdf转换pdf错误");}return null;}public static String Word2Pdf(String officePath,String OutPutPath,String officeName) {// 验证Licenseif (!getLicense(2)) {return null;}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, SaveFormat.PDF);return pdfFile.getAbsolutePath();} catch (Exception e) {e.printStackTrace();System.err.println("word转换pdf错误");}return null;}public static String PPT2Pdf(String officePath,String OutPutPath,String officeName) {// 验证Licenseif (!getLicense(3)) {return null;}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);return file.getAbsolutePath();} catch (Exception e) {e.printStackTrace();System.err.println("ppt转换pdf错误");}return null;}/*** fileTyle.equals(".DOCX") || fileTyle.equals(".DOC") || fileTyle.equals(".PPT") || fileTyle.equals(".PPTX") || fileTyle.equals(".XLS") || fileTyle.equals(".XLSX")* @param officePath* @return 返回转换以后的pdf文件路径*/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).toLowerCase(Locale.ROOT);String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";String OutPutPath = split[0].substring(0,lastNameIndex+1)+"topdf/";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>30){return Size+"MB";}//"doc", "docx", "xls","xlsx", "ppt", "pptx"try {if(officeType.equals("doc")||officeType.equals("docx")){return Word2Pdf(split[0],OutPutPath,officeName);}else if(officeType.equals("xls")||officeType.equals("xlsx")){return Excel2Pdf(split[0],OutPutPath,officeName);}else if(officeType.equals("ppt")||officeType.equals("pptx")){return PPT2Pdf(split[0],OutPutPath,officeName);}else{System.err.println("无法识别该文件");return "Error";}} catch (Exception e) {e.printStackTrace();}} else {return "NotExists";}return OutPutPath+officeName;}// public static void main(String[] args) {// OfficeToPdf("C:\\Users\\DELL\\Desktop\\桌面表格文件\\2020年沙坪坝维护.xlsx");// }}相关jar包在我的资源里面下载
调用方法将不同文件类型分类处理后发送到前端预览,不在分类中的直接发送文件下载。
public void previewFile(Integer id, HttpServletResponse response) throws IOException {FileInfo files = fileMapper.getFilesById(id);String filePate = dir + "\\" + files.getAliasName();String fileName = files.getAliasName();String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length()).toUpperCase();FileInputStream fileInputStream = new FileInputStream(filePate);int available = fileInputStream.available();if (available>(1024*1024*readonline) || fileTyle.equals(".DOCX") || fileTyle.equals(".DOC") || fileTyle.equals(".PPT") || fileTyle.equals(".PPTX") || fileTyle.equals(".XLS") || fileTyle.equals(".XLSX")) {try{//将office转换成pdf "预览";fileInputStream = new FileInputStream(AsposeUtil.OfficeToPdf(filePate));IOUtils.copy(fileInputStream, response.getOutputStream());return;}catch (Exception e){log.error("officez转换pdf预览失败"+filePate);System.err.println("officez转换pdf预览失败");}String filename = files.getFileName();filename = java.net.URLEncoder.encode(filename, "UTF-8").replace("+", "%20");response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename);IOUtils.copy(fileInputStream, response.getOutputStream());} else if (!fileTyle.equals(".PNG") && !fileTyle.equals(".JPG") && !fileTyle.equals(".JPEG") && !fileTyle.equals(".PDF")) {BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));String line;while ((line = br.readLine()) != null) {response.setContentType("text/html;charset=UTF-8");response.getWriter().write(line);response.getWriter().write("<br/>");}} else {IOUtils.copy(fileInputStream, response.getOutputStream());}}<dependency><groupId>com.aspose</groupId><artifactId>aspose.slides</artifactId><version>15.9.0</version><scope>system</scope><systemPath>${basedir}/lib/aspose.slides-15.9.0.jar</systemPath></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose.cells.java</artifactId><version>18.11</version><scope>system</scope><systemPath>${basedir}/lib/aspose-cells-java-18.11.jar</systemPath></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose.words</artifactId><version>15.8.0</version><scope>system</scope><systemPath>${basedir}/lib/aspose-words-15.8.0.jar</systemPath></dependency>
相关文章:
office文件转pdf在线预览
一、工具类 package com.sby.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 java.util.Locale;import com.aspose.cel…...

设计模式2-对象池模式
对象池模式,Object Pool Pattern,当你的应用程序需要频繁创建和销毁某种资源(比如数据库连接、线程、socket连接等)时,Object Pool 设计模式就变得很有用。它通过预先创建一组对象并将它们保存在池中,以便在…...

Oracle笔记-为表空间新增磁盘(ORA-01691)
如下报错: 原因是Oracle表空间满了,最好是新增一个存储盘。 #查XXX命名空间目前占用了多大的空间 select FILE_NAME,BYTES/1024/1024 from dba_data_files where tablespace_name XXXX #这里的FILE_NAME能查到DBF的存储位置#将对应的datafile设置为30g…...
【专业技术】高效并行分布式深度学习策略,助力模型训练与量化
尊敬的客户,您好!我们是一家专注于提供高效深度学习解决方案的专业团队,为您提供并行分布式策略、高效精调策略、大模型无损量化和高性能推理服务。 我们的服务包括: 并行分布式策略:我们的Trainer封装支持多种并行配…...
力扣-137. 只出现一次的数字 II
文章目录 力扣题目代码 力扣题目 给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。 你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。 示例 1:…...

Rust 格式化输出
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言一、format! 宏二、fmt::Debug三、fmt::Display四、? 操作符 循环打印 前言 Rust学习系列-本文根据教程学习Rust的格式化输出,包括fmt::Debug&…...
c#进程(Process)常用方法
在C#中,Process类提供了一系列用于操作进程的常用方法,以下是其中一些常用的方法: Start():启动一个新的进程。 Process.Start("notepad.exe");Kill():终止进程。 Process.GetProcessesByName("note…...

Vue源码系列讲解——虚拟DOM篇【三】(更新子节点)
1. 前言 在上一篇文章中,我们了解了Vue中的patch过程,即DOM-Diff算法。并且知道了在patch过程中基本会干三件事,分别是:创建节点,删除节点和更新节点。创建节点和删除节点都比较简单,而更新节点因为要处理…...
一个设备内存2M,一个1G大小的文件,这个文件有若干行,输出其中的带有hello的行以及行数
第一种 linux上的awk命令: awk {if($1 "113.111.211.224"){print $0}} temp.log 第二种:PHP程序yield ,和awk这个命令用的时间差不多一样,效率是很高的 $file __DIR__."/temp.log";foreach(readfilecong…...
json模块(高维数据的存储与读取)
json模块是 Python 标准库中的一个模块,用于处理 JSON(JavaScript Object Notation)格式的数据。JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。模块提供了在 Python 中进行 JSON 编码&…...

ONLYOFFICE文档8.0新功能浅探
ONLYOFFICE文档8.0新功能浅探 上个月末这个月初的几天,ONLYOFFICE版本更新了!更新到了一个比较整的大的版本号,8.0版本,看来这个生产力工具的升级速度基本上能保持每年两个版本号的速度,还是很快的,一般来…...

在vscode 中配置 pyside6 环境
在vscode中编写pyside环境配置 start 记录一下在 vscode 中编写 pyside6 程序,环境如何配置。 前提 请自行安装好 python。请自行安装好 vscode。安装 vscode 插件 Python,PYQT Integration。 配置环境 1.借助 pip 安装我们的pyside6 pip install…...
C语言:月份缩写
题目描述 从一月份到十二月的英文全称依次是:“January”,“February”,“March”,“April”,“May”,“June”,“July”,“August”,“September”,“October”,“November”,“December” 对应的缩写依次是:“Jan.”,“Feb.”,“Mar.”,“Apr.”,“Ma…...
线阵相机系列-- 1. 什么是线阵相机
线阵相机的概念 根据工业相机像素排列方式的不同,分为面阵相机和线阵相机。面阵相机的像素排列为一个完整的面,一次获取整幅二维图像,而线阵相机的像素以一条线排列,每次得到的图像呈现出一条线,通过设置扫描频率以及…...

CISCRISC? CPU架构有哪些? x86 ARM?
编者按:鉴于笔者水平有限,文中难免有不当之处,还请各位读者海涵。 是为序 我猜,常年混迹CSDN的同学应该不会没听说过CPU吧? 但你真的了解CPU吗?那笔者问你CPU有哪些架构呢? 如果你对你的答案…...
【C语言】(15)指针进阶
1. 指针与const 在C语言中,const关键字和指针一起使用时,可以创建对常量的引用,或者创建指向常量的指针。这对于保护重要数据不被意外修改以及提高程序的可读性和运行时的安全性非常有用。 1.1 const的基本用法 const关键字用于声明一个变…...

力扣精选算法100道—— 连续数组(前缀和专题)
连续数组(前缀和专题) 目录 🚩了解题意 🚩算法原理 ❗为什么hash设置成<0,-1>键值对 ❗与和为K的子数组比较hash的键值对 🚩代码实现 🚩了解题意 我们看到给定数组里面只有0和1,我们…...
flutter 国内源
Flutter 在中国由于网络原因,从官方默认的国外源下载Dart包和Flutter SDK可能会比较慢或者不稳定。为了加速依赖包的获取与Flutter SDK的安装,可以使用国内镜像源。以下是一些国内常用的Flutter和Dart包镜像源: 清华大学开源软件镜像站 Flu…...

第九个知识点:内部对象
Date对象: <script>var date new Date();date.getFullYear();//年date.getMonth();//月date.getDate();//日date.getDay();//星期几date.getHours();//时date.getMinutes();//分date.getSeconds();//秒date.getTime();//获取时间戳,时间戳时全球统一&#x…...
Android 车载应用开发之车载操作系统
一、前言 到 2030 年,全球电动汽车的销量将超过 7000 万辆,保有量将达到 3.8 亿辆,全球年度新车渗透率有望触及 60% 。这一数据来自国际能源署(IEA)发布的《全球电动汽车展望2023》。 市场趋势和政策努力的双加持下,新能源汽车来势凶猛,燃油车保有量逐年递减。此番景象…...

K8S认证|CKS题库+答案| 11. AppArmor
目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作: 1)、切换集群 2)、切换节点 3)、切换到 apparmor 的目录 4)、执行 apparmor 策略模块 5)、修改 pod 文件 6)、…...
Java如何权衡是使用无序的数组还是有序的数组
在 Java 中,选择有序数组还是无序数组取决于具体场景的性能需求与操作特点。以下是关键权衡因素及决策指南: ⚖️ 核心权衡维度 维度有序数组无序数组查询性能二分查找 O(log n) ✅线性扫描 O(n) ❌插入/删除需移位维护顺序 O(n) ❌直接操作尾部 O(1) ✅内存开销与无序数组相…...

基于uniapp+WebSocket实现聊天对话、消息监听、消息推送、聊天室等功能,多端兼容
基于 UniApp + WebSocket实现多端兼容的实时通讯系统,涵盖WebSocket连接建立、消息收发机制、多端兼容性配置、消息实时监听等功能,适配微信小程序、H5、Android、iOS等终端 目录 技术选型分析WebSocket协议优势UniApp跨平台特性WebSocket 基础实现连接管理消息收发连接…...
1688商品列表API与其他数据源的对接思路
将1688商品列表API与其他数据源对接时,需结合业务场景设计数据流转链路,重点关注数据格式兼容性、接口调用频率控制及数据一致性维护。以下是具体对接思路及关键技术点: 一、核心对接场景与目标 商品数据同步 场景:将1688商品信息…...

STM32标准库-DMA直接存储器存取
文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA(Direct Memory Access)直接存储器存取 DMA可以提供外设…...

(二)原型模式
原型的功能是将一个已经存在的对象作为源目标,其余对象都是通过这个源目标创建。发挥复制的作用就是原型模式的核心思想。 一、源型模式的定义 原型模式是指第二次创建对象可以通过复制已经存在的原型对象来实现,忽略对象创建过程中的其它细节。 📌 核心特点: 避免重复初…...

华为OD机试-食堂供餐-二分法
import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...

基于Docker Compose部署Java微服务项目
一. 创建根项目 根项目(父项目)主要用于依赖管理 一些需要注意的点: 打包方式需要为 pom<modules>里需要注册子模块不要引入maven的打包插件,否则打包时会出问题 <?xml version"1.0" encoding"UTF-8…...

uniapp微信小程序视频实时流+pc端预览方案
方案类型技术实现是否免费优点缺点适用场景延迟范围开发复杂度WebSocket图片帧定时拍照Base64传输✅ 完全免费无需服务器 纯前端实现高延迟高流量 帧率极低个人demo测试 超低频监控500ms-2s⭐⭐RTMP推流TRTC/即构SDK推流❌ 付费方案 (部分有免费额度&#x…...
【C语言练习】080. 使用C语言实现简单的数据库操作
080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...