java excel、word、PPT转换成pdf预览

news/2025/2/12 22:17:23/
先引入包:[lib下载地址](https://mp.csdn.net/mp_download/manage/download/UpDetailed)

在这里插入图片描述
在这里插入图片描述

Controllerpublic AjaxResult fileToPdf(@RequestBody VerifyCode url, HttpServletResponse response, HttpServletRequest request) throws IOException {String fileUrl = request.getScheme() + "://" + request.getServerName() + ":" + port + fileDir + url.getFileName().split("\\.")[0]+ ".pdf";String fileToPdfUrl = fileToPdf + url.getFileName().split("\\.")[0] + ".pdf";File newFile = new File(fileToPdfUrl);if(newFile.exists()){return AjaxResult.success(fileUrl);}File file = new File(fileToPdf);if(!file.exists()){file.mkdirs();}String suffix = url.getUrl().substring(url.getUrl().lastIndexOf("."));String type = FileTransForUtils.getResourceTypesDocument(suffix);if("word".equals(type)){return AjaxResult.success(FileTransForUtils.word3Pdf(url.getUrl(),response.getOutputStream(),fileToPdfUrl,fileUrl));}else if("excel".equals(type)){return AjaxResult.success(FileTransForUtils.excel3pdf(url.getUrl(), response.getOutputStream(),fileToPdfUrl,fileUrl));}else if("ppt".equals(type)){return AjaxResult.success(FileTransForUtils.ppt3pdf(url.getUrl(),response.getOutputStream(),fileToPdfUrl,fileUrl));}else {return AjaxResult.success(fileUrl);}}
package com.det.utils;import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.det.common.utils.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;import java.io.*;
import java.nio.charset.StandardCharsets;
import java.rmi.ServerException;/*** @Author: lsx* @createDate: 2023/11/5 10:49* @description:*/
public class FileTransForUtils {private static final Logger logger = LoggerFactory.getLogger(FileTransForUtils.class);//word转PDFpublic synchronized static String word3Pdf(String wordPath, OutputStream outputStream,String fileName,String fileUrl) throws ServerException {if (!getLicense("word")) {          // 验证License 若不验证则转化出的pdf文档会有水印产生throw new ServerException("验证License失败。");}try {long old = System.currentTimeMillis();InputStream inputStreamFromUrl = FileUtils.getInputStreamFromUrl(wordPath);//Address是将要被转化的word文档Document doc = new Document(inputStreamFromUrl);//新建一个pdf文档File file = new File(fileName);FileOutputStream os = new FileOutputStream(file);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,
//                doc.save(outputStream, SaveFormat.PDF);doc.save(os, SaveFormat.PDF);// XPS, SWF 相互转换long now = System.currentTimeMillis();os.close();outputStream.flush();outputStream.close();logger.info("word共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();}return fileUrl;}//excel转PDFpublic synchronized static String excel3pdf(String excelPath, OutputStream outputStream,String fileName,String fileUrl) throws ServerException {if (!getLicense("excel")) { // 验证License 若不验证则转化出的pdf文档会有水印产生throw new ServerException("验证License失败。");}try {long old = System.currentTimeMillis();InputStream inputStreamFromUrl = FileUtils.getInputStreamFromUrl(excelPath);Workbook wb = new Workbook(inputStreamFromUrl);// 原始excel路径//新建一个pdf文档File file = new File(fileName);FileOutputStream os = new FileOutputStream(file);
//                wb.save(outputStream,com.aspose.cells.SaveFormat.PDF);wb.save(os,com.aspose.cells.SaveFormat.PDF);long now = System.currentTimeMillis();outputStream.flush();outputStream.close();os.close();logger.info("excel共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();}return fileUrl;}//ppt转PDFpublic synchronized static String ppt3pdf(String pptPath, OutputStream outputStream,String fileName,String fileUrl) throws ServerException {// 验证Licenseif (!getLicense("ppt")) {throw new ServerException("验证License失败。");}FileOutputStream os = null;try {long old = System.currentTimeMillis();InputStream inputStreamFromUrl = FileUtils.getInputStreamFromUrl(pptPath);Presentation pres = new Presentation(inputStreamFromUrl);//输入ppt路径//IFontsManager fontsManager = pres.getFontsManager();//新建一个pdf文档File file = new File(fileName);os = new FileOutputStream(file);
//                pres.save(outputStream,com.aspose.slides.SaveFormat.Pdf);pres.save(os,com.aspose.slides.SaveFormat.Pdf);outputStream.flush();outputStream.close();long now = System.currentTimeMillis();logger.info("ppt共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();}finally {try {os.close();} catch (IOException e) {e.printStackTrace();}}return fileUrl;}//剔除水印private static boolean getLicense(String type) {boolean result = false;try {// 凭证String license ="<License>\n" +"  <Data>\n" +"    <Products>\n" +"      <Product>Aspose.Total for Java</Product>\n" +"      <Product>Aspose.Words for Java</Product>\n" +"    </Products>\n" +"    <EditionType>Enterprise</EditionType>\n" +"    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +"    <LicenseExpiry>20991231</LicenseExpiry>\n" +"    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +"  </Data>\n" +"  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +"</License>";InputStream is = new ByteArrayInputStream(license.getBytes(StandardCharsets.UTF_8));if(type.equals("word")){License asposeLic = new License();asposeLic.setLicense(is);}else if (type.equals("excel")){com.aspose.cells.License asposeLic = new com.aspose.cells.License();asposeLic.setLicense(is);}else if (type.equals("ppt")){com.aspose.slides.License aposeLic = new com.aspose.slides.License();aposeLic.setLicense(is);}result = true;} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();return false;}return result;}/*** 判断资源类型文档类*/public static String getResourceTypesDocument(String suffix) {String type = null;switch (suffix) {//文档类型case ".doc":case ".docx":case ".txt":type = "word";break;case ".xls":case ".xlsx":type = "excel";break;case ".ppt":case ".pptx":type = "ppt";break;}return type;}public static void main(String[] args) throws FileNotFoundException {String inputPath = "C:\\Users\\detong\\Desktop\\安全活动记录.docx";
//            String outputPath = "C:\\Users\\detong\\Desktop\\焊工作业教育培训2023.pdf";String suffix = inputPath.substring(inputPath.lastIndexOf("."));String type = getResourceTypesDocument(suffix);/*if("word".equals(type)){word3Pdf(inputPath,new FileOutputStream(new File("C:\\Users\\detong\\Desktop\\安全活动记录.word")));}else if("excel".equals(type)){excel3pdf(inputPath,new FileOutputStream(new File("C:\\Users\\detong\\Desktop\\安全活动记录.excel")));}else if("ppt".equals(type)){ppt3pdf(inputPath,new FileOutputStream(new File("C:\\Users\\detong\\Desktop\\安全活动记录.pdf")));}*/}
}

http://www.ppmy.cn/news/1212347.html

相关文章

springMVC 导出Excel ,并提供下载(处理日期格式问题)

目录 1、POI的三个依赖 2、控制层代码 3、业务层代码 4、参考文献&#xff1a; 1、POI的三个依赖 <!-- POI的三个依赖 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</vers…

Apache和Nginx实现虚拟主机的3种方式

目录 首先介绍一下Apache和nginx&#xff1a; Nginx和Apache的不同之处&#xff1a; 虚拟主机 准备工作 Apache实现&#xff1a; 方法1&#xff1a;使用不同的ip来实现 方法2&#xff1a;使用相同的ip&#xff0c;不同的端口来实现 方法3&#xff1a;使用相同的ip&…

第二章 智能家居子系统——C51单片机 配置波特率115200

前言 本章为智能家居项目的第二章&#xff0c;本章主要写51单片机的定时器timer&#xff0c;串口UART&#xff0c;中断&#xff0c;外接模块DHT11 同项目其他博文&#xff1a; 项目的概述链接&#xff1a;Linux智能家居项目概述-CSDN博客 第一章 主控代码开发链接&#xff1a…

Easypoi map方式导入数据 ,List<Map<String, String>> 日期项数据为空(null)解决办法

目录 前言解决办法 前言 在使用easypoi map的方式解析excel文件&#xff0c;若文件中的某列数据格式是日期类型&#xff0c;那么它这个工具是读取不到&#xff0c;因为它的源码读取到某列为日期格式&#xff0c;数据必须为字符串类型&#xff0c;它才会处理 switch (cell.get…

冯·诺伊曼体系结构--操作系统

文章目录 1.认识冯诺依曼系统1.1约翰冯诺依曼1.2冯诺依曼结构1.3存储器的读写速度1.4对冯诺依曼结构的认识1.5冯诺依曼结构在生活中的演示 2.操作系统--“搞管理”的软件2.1概念2.2OS存在的意义2.3管理的方式2.4系统调用和库函数概念 1.认识冯诺依曼系统 1.1约翰冯诺依曼 1.2冯…

Python与ArcGIS系列(七)自动化打印地图

目录 0 简述1 获取可用打印机列表2 打印地图3 导出地图至PDF4 导出地图至图像0 简述 本篇介绍如何利用arcpy实现获取可用打印机列表、打印地图、导出地图至PDF和图像。 1 获取可用打印机列表 通过arcpy提供的ListPrinterNames()函数可以生成可用的打印机列表。 import arcpy.m…

[ARM入门]ARM模式及其切换、异常

ARM技术特征 ARM处理器有如下特点 体积小、功耗低、成本低、性能高支持Thumb&#xff08;16位&#xff09;/ARM&#xff08;32位&#xff09;双指令集&#xff0c;能很好地兼容8位/16位器件大量使用寄存器&#xff0c;指令执行速度更快大多数数据操作都在寄存器中完成寻址方式…

linux的sftp复制传输文件

连接远程服务器 sftp -P 端口号 用户名主机 例如&#xff1a;sftp -P 80 ubuntu172.168.0.1 并按照提示输入密码 分别使用命令查看本地当前路径&#xff08;Local&#xff09; 和远程路径&#xff08;Remote&#xff09; pwd lpwd 使用 cd 远程路径和 lcd 本地路径分别进入对…