其实还有一种spire转化PDF,不过这种是收费的还有限制只能导出3个sheet页数据也有限制

1.使用jacob

1.1引入依赖

        <!--jacob依赖--><dependency><groupId>com.jacob</groupId><artifactId>jacob</artifactId><version>1.19</version><scope>system</scope><!--本地的jacob.jar的路径--><systemPath>D:/kaifa/jacob-1.20/jacob-1.20/jacob.jar</systemPath></dependency>

1.2 工具类

package com.qiang;import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;/*** @ClassName: OfficeToPDF  * @author yinzl* @date 2020-05-23* 调用Microsoft excel,必须安装Microsoft Offcie 2007以上版本* 需要引入jar包:jacob.jar,解压jacob_1.19.zip ,将文件jacob-1.19-x64.dll  放到jdk安装目录bin文件夹下, jdk要求1.8* 如果出现不能设置类 PageSetup 的 PaperSize 属性的问题,是因为打印机设置中没有任何打印机的原因,使得页面设置失败,在添加任意打印机后,程序运行正常* */
public class OfficeToPDF {private static final Integer WORD_TO_PDF_OPERAND = 17;private static final Integer PPT_TO_PDF_OPERAND = 32;private static final Integer EXCEL_TO_PDF_OPERAND = 0;public static void doc2pdf(String srcFilePath, String pdfFilePath) throws Exception {  ActiveXComponent app = null;  Dispatch doc = null;  try {  ComThread.InitSTA();  app = new ActiveXComponent("Word.Application");  app.setProperty("Visible", false);  Dispatch docs = app.getProperty("Documents").toDispatch(); Object[] obj = new Object[]{srcFilePath, new Variant(false),  new Variant(false),//是否只读  new Variant(false),   new Variant("pwd")};doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
//          Dispatch.put(doc, "Compatibility", false);  //兼容性检查,为特定值false不正确  Dispatch.put(doc, "RemovePersonalInformation", false);  Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, WORD_TO_PDF_OPERAND); // word保存为pdf格式宏,值为17  }catch (Exception e) {  e.printStackTrace();throw e;} finally {  if (doc != null) {  Dispatch.call(doc, "Close", false);  }  if (app != null) {  app.invoke("Quit", 0);  }  ComThread.Release();  }  }  public static void ppt2pdf(String srcFilePath, String pdfFilePath) throws Exception {ActiveXComponent app = null;Dispatch ppt = null;try {ComThread.InitSTA();app = new ActiveXComponent("PowerPoint.Application");Dispatch ppts = app.getProperty("Presentations").toDispatch();/** call * param 4: ReadOnly* param 5: Untitled指定文件是否有标题* param 6: WithWindow指定文件是否可见* */ppt = Dispatch.call(ppts, "Open", srcFilePath, true,true, false).toDispatch();Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND); // ppSaveAsPDF为特定值32} catch (Exception e) {e.printStackTrace();throw e;} finally {if (ppt != null) {Dispatch.call(ppt, "Close");}if (app != null) {app.invoke("Quit");}ComThread.Release();}}public static boolean excel2Pdf(String inFilePath, String outFilePath) throws Exception {ActiveXComponent ax = null;Dispatch excel = null;try {ComThread.InitSTA();ax = new ActiveXComponent("Excel.Application");ax.setProperty("Visible", new Variant(false));ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏Dispatch excels = ax.getProperty("Workbooks").toDispatch();Object[] obj = new Object[]{ inFilePath, new Variant(false),new Variant(false) };excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();//将excel表格 设置成A3的大小Dispatch sheets = Dispatch.call(excel, "Worksheets").toDispatch();  Dispatch sheet = Dispatch.call(sheets, "Item", new Integer(1)).toDispatch();  Dispatch pageSetup = Dispatch.call(sheet, "PageSetup").toDispatch();//Dispatch.put(pageSetup, "PaperSize", new Integer(8));//A3是8,A4是9,A5是11等等  //该行代码报错:不能设置类 PageSetup 的 PaperSize 属性,暂时关闭// 转换格式Object[] obj2 = new Object[]{ new Variant(EXCEL_TO_PDF_OPERAND), // PDF格式=0outFilePath, new Variant(0)  //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件};Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);} catch (Exception es) {es.printStackTrace();return false;// throw es;} finally {if (excel != null) {Dispatch.call(excel, "Close", new Variant(false));}if (ax != null) {ax.invoke("Quit", new Variant[] {});ax = null;}ComThread.Release();}return true;}public static void main(String[] args){String inFilePath = "D:\\temp\\456dda29f26f45e2878c99b5af5d489b.xlsx";String outFilePath = "D:\\temp\\test.pdf";try {OfficeToPDF.excel2Pdf(inFilePath,outFilePath);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

1.3 测试 拿出提前准备好的excel文件

1.4运行

    @Testpublic void test5() throws Exception {long old = System.currentTimeMillis();String inFilePath="C:\\Users\\ex_lizhq5\\Downloads\\用户-导出.xlsx";OfficeToPDF.excel2Pdf(inFilePath,"C:\\Users\\ex_lizhq5\\Downloads\\用户-导出.pdf");long now = System.currentTimeMillis();//共耗时:33.234秒 33.4System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时}  

1.6结果

2.使用aspose

2.1引入依赖

        <dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>20.7</version><classifier>jdk17</classifier></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-slides</artifactId><version>20.7</version><classifier>jdk16</classifier></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>20.7</version></dependency><repositories><repository><id>AsposeJavaAPI</id><name>Aspose Java API</name><url>https://repository.aspose.com/repo/</url></repository></repositories>

2.2 编写工具类

package com.qiang;import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;public class PdfUtil {public static File Pdf(ArrayList<String> imageUrllist,String mOutputPdfFileName) {//Document doc = new Document(PageSize.A4, 20, 20, 20, 20); // new一个pdf文档com.itextpdf.text.Document doc = new com.itextpdf.text.Document();try {PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); // pdf写入doc.open();// 打开文档for (int i = 0; i < imageUrllist.size(); i++) { // 循环图片List,将图片加入到pdf中doc.newPage(); // 在pdf创建一页Image png1 = Image.getInstance(imageUrllist.get(i)); // 通过文件路径获取imagefloat heigth = png1.getHeight();float width = png1.getWidth();int percent = getPercent2(heigth, width);png1.setAlignment(Image.MIDDLE);png1.scalePercent(percent + 3);// 表示是原来图像的比例;doc.add(png1);}doc.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}File mOutputPdfFile = new File(mOutputPdfFileName); // 输出流if (!mOutputPdfFile.exists()) {mOutputPdfFile.deleteOnExit();return null;}return mOutputPdfFile; // 反回文件输出流}public static int getPercent(float h, float w) {int p = 0;float p2 = 0.0f;if (h > w) {p2 = 297 / h * 100;} else {p2 = 210 / w * 100;}p = Math.round(p2);return p;}public static int getPercent2(float h, float w) {int p = 0;float p2 = 0.0f;p2 = 530 / w * 100;p = Math.round(p2);return p;}/*** 图片文件转PDF* @param filepath* @param request* @return*/public static String imgOfPdf(String filepath, HttpServletRequest request) {boolean result = false;String pdfUrl = "";String fileUrl = "";try {ArrayList<String> imageUrllist = new ArrayList<String>(); // 图片list集合imageUrllist.add(request.getSession().getServletContext().getRealPath(File.separator + filepath)); // 添加图片文件路径String fles = filepath.substring(0, filepath.lastIndexOf("."));pdfUrl = request.getSession().getServletContext().getRealPath(File.separator +fles + ".pdf"); // 输出pdf文件路径fileUrl =fles+".pdf";result = true;if (result == true) {File file = PdfUtil.Pdf(imageUrllist, pdfUrl);// 生成pdffile.createNewFile();}} catch (IOException e) {e.printStackTrace();}return fileUrl;}public static void doc2pdf(String Address, String outPath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();File file = new File(outPath); // 新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(Address); // Address是将要被转化的word文档doc.save(os,SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML,// OpenDocument, PDF, EPUB, XPS, SWF// 相互转换long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时os.close();} catch (Exception e) {e.printStackTrace();}}public static boolean getLicense() {boolean result = false;try {InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static String docOfPdf(String filePath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return "PDF格式转化失败";}try {long old = System.currentTimeMillis();//获取路径参数String filePath1 =  filePath;String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));String pdfSPath = filePath2+".pdf";filePath2 = pdfSPath; // 输出pdf文件路径File file = new File(filePath2); // 新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(filePath1); // Address是将要被转化的word文档doc.save(os,SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML,// OpenDocument, PDF, EPUB, XPS, SWF// 相互转换long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时os.close();return pdfSPath;} catch (Exception e) {e.printStackTrace();}return "PDF格式转化失败";}public static boolean getLicense1() {boolean result = false;try {InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下com.aspose.cells.License aposeLic = new com.aspose.cells.License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** @param excelPath* @param pdfPath*/public static String exceOfPdf(String filePath) {if (!getLicense1()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return "PDF格式转化失败";}try {long old = System.currentTimeMillis();//获取路径参数String filePath1 =  filePath;String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));String pdfSPath = filePath2+".pdf";filePath2 = pdfSPath; // 输出pdf文件路径//文件操作File file = new File(filePath2); // 新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Workbook wb = new Workbook(filePath1);// 原始excel路径FileOutputStream fileOS = new FileOutputStream(file);wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);fileOS.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时return pdfSPath;} catch (Exception e) {e.printStackTrace();}return "PDF格式转化失败";}public static boolean getLicense2() {boolean result = false;try {InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下com.aspose.slides.License aposeLic = new com.aspose.slides.License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/**** @param args*///public static void ppt2pdf(String Address) {public static String pptOfpdf(String filePath, HttpServletRequest request){// 验证Licenseif (!getLicense2()) {return "PDF格式转化失败";}try {long old = System.currentTimeMillis();//File file = new File("C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/generic/web/file/pdf1.pdf");// 输出pdf路径//com.aspose.slides.Presentation pres = new  com.aspose.slides.Presentation(Address);//输入pdf路径String filePath1 =  request.getSession().getServletContext().getRealPath(File.separator  + filePath);String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));String pdfPathString  = filePath2 + ".pdf";filePath2 = request.getSession().getServletContext().getRealPath(File.separator  + filePath2 + ".pdf"); // 输出pdf文件路径//文件操作File file = new File(filePath2); // 新建一个空白pdf文档com.aspose.slides.Presentation pres = new  com.aspose.slides.Presentation(filePath1);//输入pdf路径FileOutputStream fileOS = new FileOutputStream(file);pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);fileOS.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + file.getPath()); //转化过程耗时return pdfPathString;} catch (Exception e) {e.printStackTrace();}return "PDF格式转化失败";}
}

2.3 准备生成好的excel文件,还是上面那个

2.4 测试

    @Testpublic void test3() throws IOException {String inFilePath="C:\\Users\\ex_lizhq5\\Downloads\\用户-导出 (2).xlsx";//String outFilePath="D://wcmis_file/email/井控安全风险分级管控台账(2022年5月).pdf";//OfficeToPDF.excel2Pdf(inFilePath,outFilePath);//aspose  56s 56.869PdfUtil.exceOfPdf(inFilePath);
//        long old = System.currentTimeMillis();
//        IFileConvert fileConvert = FileConvertEnum.getFileConvert("EXCEL");
//        String pdfUri = fileConvert.fileToPdf("C:\\Users\\ex_lizhq5\\Downloads\\用户-导出.xlsx");
//        long now = System.currentTimeMillis();
//
//        System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时}

2.5 结果

springboot java8使用jacob,aspose两种方式实现excel、word转pdf相关推荐

  1. SpringBoot实现多数据源的两种方式

    前言 公司项目有连接多个不同数据库的需求,特研究了一下,根据网上的资料,造了一个基于AOP方式的数据源切换轮子,但继续探索,突然发现有开源的多数据源管理启动器.不过,本篇两种方式都会介绍. 基于dyn ...

  2. Springboot中数据库访问的两种方式之-JdbcTemplate

    目录 01.写在前面 02.项目依赖 03.创建模型脚本 04.读取数据库 05.Controller 06.开始测试 本文由bingo创作,授权我原创发布. Tiger和他朋友们的原创技术文章,请关 ...

  3. SpringBoot中使用AMQ的两种方式(Java配置、注解方式)

    Java配置方式使用AMQ 1. 引入依赖(pom.xml) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns ...

  4. SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)

    使用@JmsListener注解方式 1. 工程目录 2. 引入依赖 <?xml version="1.0" encoding="UTF-8"?> ...

  5. SpringBoot之——热部署的两种方式

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/69940574 一.热部署 在项目开发过程中,常常会改动页面数据或者修改数据结构,为 ...

  6. 两种方式导入excel

    第一种 easyExcel pom文件导入 com.alibaba easyexcel 2.2.3 然后 /** * 导入用户excel * @param * @return */ @PostMapp ...

  7. 继承WebMvcConfigurer 和 WebMvcConfigurerAdapter类依然CORS报错? springboot 两种方式稳定解决跨域问题

    继承WebMvcConfigurer 和 WebMvcConfigurerAdapter类依然CORS报错???springboot 两种方式稳定解决跨域问题! 之前我写了一篇文章,来解决CORS报错 ...

  8. 【SpringBoot】项目实现热部署的两种方式

    前言 spring boot : 2.0.0.RELEASE maven eclipse 另外还需清楚什么是热部署,以及为什么要热部署. SpringBoot项目中实现热部署的两种方式,使得部署变得异 ...

  9. 快速搭建Springboot项目的两种方式!!

    大家好,我是雄雄,欢迎关注微信公众号[雄雄的小课堂]. 前言 Springboot的特点就是简单.快速和方便,使用idea不到一分钟就可以快速搭建springboot项目,并且,在这里,你不用写spr ...

最新文章

  1. 性能全面超数据库专家,腾讯提基于机器学习的性能优化系统 | SIGMOD 2019
  2. PrintWriter用法简析
  3. Qt学习笔记之常用控件QlistWidget
  4. .Net之美读书笔记17
  5. 《神经网络与深度学习》课程笔记(2)-- 神经网络基础之逻辑回归
  6. java获取微信用户信息(UnionID)
  7. java 设置表头字体_Java将数据按列写入Excel并设置格式(字体、背景色、自动列宽、对齐方式等)...
  8. Android编码架构MVx演进历史
  9. SpringBoot自动装配的魔力
  10. 今日收获 可以点击的标签 鼠标悬浮 小手图标
  11. 【论文】GC-MC论文相关
  12. 数据结构实验——顺序表操作
  13. 为什么说期货交易者依靠程序化交易系统接口才能获得成功
  14. 机器学习 上网时长分析
  15. QT调用opencv的videowrite类输出生成视频打不开(已解决)
  16. STC8H8K64U学习(自用)
  17. 李沐深度学习Accumulator函数
  18. 高斯——克吕格投影正算
  19. 2020最新kali安装中文输入法
  20. r语言各形状编号_R语言plot()函数的符号、颜色和尺寸

热门文章

  1. 百度糯米app中关闭网页或窗口的方法,99%的人都不知道,网上也找不到
  2. 七牛云 X FaceU 激萌:自拍软件玩起了短视频社交,AI 内容审核献助攻
  3. RapidShare使用教程
  4. 1分钟学会 2 个复制文本到剪贴板的方法
  5. java获取系统硬件温度,zabbix通过IPMI监控硬件环境(温度和风扇)
  6. 【资料分享】《建筑给水排水设计标准》(GB50015-2019)
  7. 分布式无线全向麦克风型号:MHD-G3B-14M
  8. Android修行手册 - GridLayout复习和计算器示例
  9. 大学四年生活总结_大学四年,我总结了一个道理,多米诺骨牌效应
  10. 计算机点关机无法关闭主机,为什么win7电脑关不了机怎么办_win7关机主机还在运行解决方法...