当前位置: 首页 > 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>

相关文章:

  • 【前端高频面试题--Vue基础篇】
  • 多模态对比语言图像预训练CLIP:打破语言与视觉的界限,具备零样本能力
  • 猫头虎分享已解决Bug || 未定义的变量(Undefined Variable):ReferenceError: x is not defined
  • 获取旁站 / C 段:第三方网站(附链接)
  • 天猫数据分析(天猫数据查询工具):2023年滑雪服市场消费现状及趋势(天猫服饰行业分析报告)
  • php 函数三
  • 新型RedAlert勒索病毒针对VMWare ESXi服务器
  • 利用LLM大模型生成sql的深入应用探究
  • 新增同步管理、操作日志模块,支持公共链接分享,DataEase开源数据可视化分析平台v2.3.0发布
  • 版本控制工具——Git
  • PySpark(四)PySpark SQL、Catalyst优化器、Spark SQL的执行流程、Spark新特性
  • 【Kotlin】Kotlin环境搭建
  • 【SQL高频基础题】619.只出现一次的最大数字
  • 【大数据面试题】005 谈一谈 Flink Watermark 水印
  • 消息中间件:Puslar、Kafka、RabbigMQ、ActiveMQ
  • 【Linux系统编程】快速查找errno错误码信息
  • gops —— Go 程序诊断分析工具
  • JavaScript DOM 10 - 滚动
  • Vue2 SSR 的优化之旅
  • Web Storage相关
  • 反思总结然后整装待发
  • 京东美团研发面经
  • 开发基于以太坊智能合约的DApp
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 猫头鹰的深夜翻译:Java 2D Graphics, 简单的仿射变换
  • 一道面试题引发的“血案”
  • #AngularJS#$sce.trustAsResourceUrl
  • #DBA杂记1
  • #Java第九次作业--输入输出流和文件操作
  • (Bean工厂的后处理器入门)学习Spring的第七天
  • (附源码)springboot“微印象”在线打印预约系统 毕业设计 061642
  • (一)UDP基本编程步骤
  • .NET 5.0正式发布,有什么功能特性(翻译)
  • .NET CLR Hosting 简介
  • .net web项目 调用webService
  • .NET/C# 使窗口永不获得焦点
  • .NET3.5下用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke(转)
  • /etc/fstab和/etc/mtab的区别
  • @requestBody写与不写的情况
  • @vue/cli脚手架
  • @开发者,一文搞懂什么是 C# 计时器!
  • [AutoSAR 存储] 汽车智能座舱的存储需求
  • [C/C++] -- 二叉树
  • [CISCN2019 华东南赛区]Web11
  • [Codeforces] combinatorics (R1600) Part.2
  • [daily][archlinux][game] 几个linux下还不错的游戏
  • [IMX6DL] CPU频率调节模式以及降频方法
  • [JavaWeb学习] idea新建web项目
  • [leetcode]Search a 2D Matrix @ Python
  • [leetcode]Symmetric Tree
  • [Linux] MySQL数据库之索引
  • [mit6.s081] 笔记 Lab2:system calls
  • [Oh My C++ Diary]return 1和return 0的区别
  • [one_demo_18]js定时器的示例
  • [openGL]在ubuntu20.06上搭建openGL环境