当前位置: 首页 > news >正文

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-对象池模式

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

Oracle笔记-为表空间新增磁盘(ORA-01691)

如下报错&#xff1a; 原因是Oracle表空间满了&#xff0c;最好是新增一个存储盘。 #查XXX命名空间目前占用了多大的空间 select FILE_NAME,BYTES/1024/1024 from dba_data_files where tablespace_name XXXX #这里的FILE_NAME能查到DBF的存储位置#将对应的datafile设置为30g…...

【专业技术】高效并行分布式深度学习策略,助力模型训练与量化

尊敬的客户&#xff0c;您好&#xff01;我们是一家专注于提供高效深度学习解决方案的专业团队&#xff0c;为您提供并行分布式策略、高效精调策略、大模型无损量化和高性能推理服务。 我们的服务包括&#xff1a; 并行分布式策略&#xff1a;我们的Trainer封装支持多种并行配…...

力扣-137. 只出现一次的数字 II

文章目录 力扣题目代码 力扣题目 给你一个整数数组 nums &#xff0c;除某个元素仅出现 一次 外&#xff0c;其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。 你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。 示例 1&#xff1a;…...

Rust 格式化输出

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、format! 宏二、fmt::Debug三、fmt::Display四、? 操作符 循环打印 前言 Rust学习系列-本文根据教程学习Rust的格式化输出&#xff0c;包括fmt::Debug&…...

c#进程(Process)常用方法

在C#中&#xff0c;Process类提供了一系列用于操作进程的常用方法&#xff0c;以下是其中一些常用的方法&#xff1a; Start()&#xff1a;启动一个新的进程。 Process.Start("notepad.exe");Kill()&#xff1a;终止进程。 Process.GetProcessesByName("note…...

Vue源码系列讲解——虚拟DOM篇【三】(更新子节点)

1. 前言 在上一篇文章中&#xff0c;我们了解了Vue中的patch过程&#xff0c;即DOM-Diff算法。并且知道了在patch过程中基本会干三件事&#xff0c;分别是&#xff1a;创建节点&#xff0c;删除节点和更新节点。创建节点和删除节点都比较简单&#xff0c;而更新节点因为要处理…...

一个设备内存2M,一个1G大小的文件,这个文件有若干行,输出其中的带有hello的行以及行数

第一种 linux上的awk命令&#xff1a; awk {if($1 "113.111.211.224"){print $0}} temp.log 第二种&#xff1a;PHP程序yield &#xff0c;和awk这个命令用的时间差不多一样&#xff0c;效率是很高的 $file __DIR__."/temp.log";foreach(readfilecong…...

json模块(高维数据的存储与读取)

json模块是 Python 标准库中的一个模块&#xff0c;用于处理 JSON&#xff08;JavaScript Object Notation&#xff09;格式的数据。JSON是一种轻量级的数据交换格式&#xff0c;易于人阅读和编写&#xff0c;同时也易于机器解析和生成。模块提供了在 Python 中进行 JSON 编码&…...

ONLYOFFICE文档8.0新功能浅探

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

在vscode 中配置 pyside6 环境

在vscode中编写pyside环境配置 start 记录一下在 vscode 中编写 pyside6 程序&#xff0c;环境如何配置。 前提 请自行安装好 python。请自行安装好 vscode。安装 vscode 插件 Python&#xff0c;PYQT Integration。 配置环境 1.借助 pip 安装我们的pyside6 pip install…...

C语言:月份缩写

题目描述 从一月份到十二月的英文全称依次是&#xff1a;“January”,“February”,“March”,“April”,“May”,“June”,“July”,“August”,“September”,“October”,“November”,“December” 对应的缩写依次是&#xff1a;“Jan.”,“Feb.”,“Mar.”,“Apr.”,“Ma…...

线阵相机系列-- 1. 什么是线阵相机

线阵相机的概念 根据工业相机像素排列方式的不同&#xff0c;分为面阵相机和线阵相机。面阵相机的像素排列为一个完整的面&#xff0c;一次获取整幅二维图像&#xff0c;而线阵相机的像素以一条线排列&#xff0c;每次得到的图像呈现出一条线&#xff0c;通过设置扫描频率以及…...

CISCRISC? CPU架构有哪些? x86 ARM?

编者按&#xff1a;鉴于笔者水平有限&#xff0c;文中难免有不当之处&#xff0c;还请各位读者海涵。 是为序 我猜&#xff0c;常年混迹CSDN的同学应该不会没听说过CPU吧&#xff1f; 但你真的了解CPU吗&#xff1f;那笔者问你CPU有哪些架构呢&#xff1f; 如果你对你的答案…...

【C语言】(15)指针进阶

1. 指针与const 在C语言中&#xff0c;const关键字和指针一起使用时&#xff0c;可以创建对常量的引用&#xff0c;或者创建指向常量的指针。这对于保护重要数据不被意外修改以及提高程序的可读性和运行时的安全性非常有用。 1.1 const的基本用法 const关键字用于声明一个变…...

力扣精选算法100道—— 连续数组(前缀和专题)

连续数组&#xff08;前缀和专题&#xff09; 目录 &#x1f6a9;了解题意 &#x1f6a9;算法原理 ❗为什么hash设置成<0,-1>键值对 ❗与和为K的子数组比较hash的键值对 &#x1f6a9;代码实现 &#x1f6a9;了解题意 我们看到给定数组里面只有0和1&#xff0c;我们…...

flutter 国内源

Flutter 在中国由于网络原因&#xff0c;从官方默认的国外源下载Dart包和Flutter SDK可能会比较慢或者不稳定。为了加速依赖包的获取与Flutter SDK的安装&#xff0c;可以使用国内镜像源。以下是一些国内常用的Flutter和Dart包镜像源&#xff1a; 清华大学开源软件镜像站 Flu…...

第九个知识点:内部对象

Date对象: <script>var date new Date();date.getFullYear();//年date.getMonth();//月date.getDate();//日date.getDay();//星期几date.getHours();//时date.getMinutes();//分date.getSeconds();//秒date.getTime();//获取时间戳&#xff0c;时间戳时全球统一&#x…...

Android 车载应用开发之车载操作系统

一、前言 到 2030 年,全球电动汽车的销量将超过 7000 万辆,保有量将达到 3.8 亿辆,全球年度新车渗透率有望触及 60% 。这一数据来自国际能源署(IEA)发布的《全球电动汽车展望2023》。 市场趋势和政策努力的双加持下,新能源汽车来势凶猛,燃油车保有量逐年递减。此番景象…...

业务系统对接大模型的基础方案:架构设计与关键步骤

业务系统对接大模型&#xff1a;架构设计与关键步骤 在当今数字化转型的浪潮中&#xff0c;大语言模型&#xff08;LLM&#xff09;已成为企业提升业务效率和创新能力的关键技术之一。将大模型集成到业务系统中&#xff0c;不仅可以优化用户体验&#xff0c;还能为业务决策提供…...

微信小程序之bind和catch

这两个呢&#xff0c;都是绑定事件用的&#xff0c;具体使用有些小区别。 官方文档&#xff1a; 事件冒泡处理不同 bind&#xff1a;绑定的事件会向上冒泡&#xff0c;即触发当前组件的事件后&#xff0c;还会继续触发父组件的相同事件。例如&#xff0c;有一个子视图绑定了b…...

【解密LSTM、GRU如何解决传统RNN梯度消失问题】

解密LSTM与GRU&#xff1a;如何让RNN变得更聪明&#xff1f; 在深度学习的世界里&#xff0c;循环神经网络&#xff08;RNN&#xff09;以其卓越的序列数据处理能力广泛应用于自然语言处理、时间序列预测等领域。然而&#xff0c;传统RNN存在的一个严重问题——梯度消失&#…...

Opencv中的addweighted函数

一.addweighted函数作用 addweighted&#xff08;&#xff09;是OpenCV库中用于图像处理的函数&#xff0c;主要功能是将两个输入图像&#xff08;尺寸和类型相同&#xff09;按照指定的权重进行加权叠加&#xff08;图像融合&#xff09;&#xff0c;并添加一个标量值&#x…...

华为OD机考-机房布局

import java.util.*;public class DemoTest5 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseSystem.out.println(solve(in.nextLine()));}}priv…...

Go语言多线程问题

打印零与奇偶数&#xff08;leetcode 1116&#xff09; 方法1&#xff1a;使用互斥锁和条件变量 package mainimport ("fmt""sync" )type ZeroEvenOdd struct {n intzeroMutex sync.MutexevenMutex sync.MutexoddMutex sync.Mutexcurrent int…...

医疗AI模型可解释性编程研究:基于SHAP、LIME与Anchor

1 医疗树模型与可解释人工智能基础 医疗领域的人工智能应用正迅速从理论研究转向临床实践,在这一过程中,模型可解释性已成为确保AI系统被医疗专业人员接受和信任的关键因素。基于树模型的集成算法(如RandomForest、XGBoost、LightGBM)因其卓越的预测性能和相对良好的解释性…...

EasyRTC音视频实时通话功能在WebRTC与智能硬件整合中的应用与优势

一、WebRTC与智能硬件整合趋势​ 随着物联网和实时通信需求的爆发式增长&#xff0c;WebRTC作为开源实时通信技术&#xff0c;为浏览器与移动应用提供免插件的音视频通信能力&#xff0c;在智能硬件领域的融合应用已成必然趋势。智能硬件不再局限于单一功能&#xff0c;对实时…...

简约商务通用宣传年终总结12套PPT模版分享

IOS风格企业宣传PPT模版&#xff0c;年终工作总结PPT模版&#xff0c;简约精致扁平化商务通用动画PPT模版&#xff0c;素雅商务PPT模版 简约商务通用宣传年终总结12套PPT模版分享:商务通用年终总结类PPT模版https://pan.quark.cn/s/ece1e252d7df...

02-性能方案设计

需求分析与测试设计 根据具体的性能测试需求&#xff0c;确定测试类型&#xff0c;以及压测的模块(web/mysql/redis/系统整体)前期要与相关人员充分沟通&#xff0c;初步确定压测方案及具体的性能指标QA完成性能测试设计后&#xff0c;需产出测试方案文档发送邮件到项目组&…...