当前位置: 首页 > 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》。 市场趋势和政策努力的双加持下,新能源汽车来势凶猛,燃油车保有量逐年递减。此番景象…...

设计模式和设计原则回顾

设计模式和设计原则回顾 23种设计模式是设计原则的完美体现,设计原则设计原则是设计模式的理论基石, 设计模式 在经典的设计模式分类中(如《设计模式:可复用面向对象软件的基础》一书中),总共有23种设计模式,分为三大类: 一、创建型模式(5种) 1. 单例模式(Sing…...

label-studio的使用教程(导入本地路径)

文章目录 1. 准备环境2. 脚本启动2.1 Windows2.2 Linux 3. 安装label-studio机器学习后端3.1 pip安装(推荐)3.2 GitHub仓库安装 4. 后端配置4.1 yolo环境4.2 引入后端模型4.3 修改脚本4.4 启动后端 5. 标注工程5.1 创建工程5.2 配置图片路径5.3 配置工程类型标签5.4 配置模型5.…...

8k长序列建模,蛋白质语言模型Prot42仅利用目标蛋白序列即可生成高亲和力结合剂

蛋白质结合剂&#xff08;如抗体、抑制肽&#xff09;在疾病诊断、成像分析及靶向药物递送等关键场景中发挥着不可替代的作用。传统上&#xff0c;高特异性蛋白质结合剂的开发高度依赖噬菌体展示、定向进化等实验技术&#xff0c;但这类方法普遍面临资源消耗巨大、研发周期冗长…...

【大模型RAG】Docker 一键部署 Milvus 完整攻略

本文概要 Milvus 2.5 Stand-alone 版可通过 Docker 在几分钟内完成安装&#xff1b;只需暴露 19530&#xff08;gRPC&#xff09;与 9091&#xff08;HTTP/WebUI&#xff09;两个端口&#xff0c;即可让本地电脑通过 PyMilvus 或浏览器访问远程 Linux 服务器上的 Milvus。下面…...

Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务

通过akshare库&#xff0c;获取股票数据&#xff0c;并生成TabPFN这个模型 可以识别、处理的格式&#xff0c;写一个完整的预处理示例&#xff0c;并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务&#xff0c;进行预测并输…...

跨链模式:多链互操作架构与性能扩展方案

跨链模式&#xff1a;多链互操作架构与性能扩展方案 ——构建下一代区块链互联网的技术基石 一、跨链架构的核心范式演进 1. 分层协议栈&#xff1a;模块化解耦设计 现代跨链系统采用分层协议栈实现灵活扩展&#xff08;H2Cross架构&#xff09;&#xff1a; 适配层&#xf…...

python爬虫:Newspaper3k 的详细使用(好用的新闻网站文章抓取和解析的Python库)

更多内容请见: 爬虫和逆向教程-专栏介绍和目录 文章目录 一、Newspaper3k 概述1.1 Newspaper3k 介绍1.2 主要功能1.3 典型应用场景1.4 安装二、基本用法2.2 提取单篇文章的内容2.2 处理多篇文档三、高级选项3.1 自定义配置3.2 分析文章情感四、实战案例4.1 构建新闻摘要聚合器…...

Java多线程实现之Thread类深度解析

Java多线程实现之Thread类深度解析 一、多线程基础概念1.1 什么是线程1.2 多线程的优势1.3 Java多线程模型 二、Thread类的基本结构与构造函数2.1 Thread类的继承关系2.2 构造函数 三、创建和启动线程3.1 继承Thread类创建线程3.2 实现Runnable接口创建线程 四、Thread类的核心…...

C++.OpenGL (14/64)多光源(Multiple Lights)

多光源(Multiple Lights) 多光源渲染技术概览 #mermaid-svg-3L5e5gGn76TNh7Lq {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-3L5e5gGn76TNh7Lq .error-icon{fill:#552222;}#mermaid-svg-3L5e5gGn76TNh7Lq .erro…...

Unity UGUI Button事件流程

场景结构 测试代码 public class TestBtn : MonoBehaviour {void Start(){var btn GetComponent<Button>();btn.onClick.AddListener(OnClick);}private void OnClick(){Debug.Log("666");}}当添加事件时 // 实例化一个ButtonClickedEvent的事件 [Formerl…...