目录

  • 1、加载Aspose包
  • 2、配置license
  • 2、word转pdf
  • 3、excel转pdf

1、加载Aspose包

1、下载:
Aspose官网没有提供相应的maven地址,所有手动引入jar包:

  • aspose-cells-20.4 - c.jar
  • aspose-words-18.10-jdk16.jar

下载地址:https://download.csdn.net/download/zhuocailing3390/76147206

2、配置lib目录:
在项目的resources目录下,创建lib目录,并且将下载的两个jar包放入其中

3、引入pom:
引入自定义配置的maven坐标:

 <dependencys><dependency><groupId>com.aspose.cells</groupId><artifactId>aspose-cells</artifactId><version>20.4 - c</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-20.4 - c.jar</systemPath></dependency><dependency><groupId>com.aspose.words</groupId><artifactId>aspose-words</artifactId><version>words-18.10-jdk16</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jar</systemPath></dependency></dependencys>

2、配置license

resources目录下创建license.xml文件,代码如下:

<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

2、word转pdf

封装工具类:

import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;import javax.servlet.http.HttpServletResponse;
import java.io.*;/*** @Author: LiHuaZhi* @Date: 2021/7/13 14:21* @Description:**/
public class Doc2PdfUtil {/*** 加载授权配置文件** @return*/private static boolean getLicense() {boolean result = false;try (InputStream in = Doc2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) {// License的包路径必须为com.aspose.words.LicenseLicense license = new License();license.setLicense(in);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** doc转pdf** @param inputStream* @param fileName* @param response* @return*/public static void doc2Pdf(InputStream inputStream,String fileName, HttpServletResponse response) {System.out.println("pdf转换中...");long old = System.currentTimeMillis();try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {// 验证if (!getLicense()) {throw new RuntimeException("文件转换失败!");}// 加载字体FontSettings settings = FontSettings.getDefaultInstance();settings.setFontsFolder("C:\\Windows\\Fonts", true);LoadOptions loadOptions = new LoadOptions();loadOptions.setFontSettings(settings);// 也可以直接指定路径 document = new Document(docPath);Document document = new Document(inputStream, loadOptions);//  DocumentBuilder builder = new DocumentBuilder(document);// 设置纸张大小//  builder.getPageSetup().setPaperSize(PaperSize.A3);// 设置横向// builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);document.save(fos, SaveFormat.PDF);response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));byte[] buffer = fos.toByteArray();InputStream arrayInputStream = new ByteArrayInputStream(buffer);byte[] buf = new byte[4096];int len = -1;while ((len = arrayInputStream.read(buf)) != -1) {response.getOutputStream().write(buf, 0, len);}long now = System.currentTimeMillis();System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");} catch (Exception e) {e.printStackTrace();throw new RuntimeException("文件转换失败!");} finally {try {if (inputStream != null) {inputStream.close();}} catch (IOException e) {e.printStackTrace();}}}
}

Controller实现:

@RestController
@RequestMapping("/test")
public class TestController {/*** 导入word文件** @param file* @return* @throws Exception*/@RequestMapping("/word")@ResponseBodypublic void uploadWord(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {if (file.isEmpty()) {return;}String originalFilename = file.getOriginalFilename();String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));Doc2PdfUtil.doc2Pdf(file.getInputStream(), fileName, response);}
}

postMan测试:
请求接口,比如:http://127.0.0.1:9090/test/word

3、excel转pdf

封装工具类:

import com.aspose.cells.*;
import com.aspose.words.Document;import javax.servlet.http.HttpServletResponse;
import java.io.*;public class Excel2PdfUtil {/*** 加载配置文件** @return*/private static boolean getLicense() {boolean result = false;try (InputStream in = Excel2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) {// License的包路径必须为com.aspose.cells.LicenseLicense license = new License();license.setLicense(in);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** @param inputStream* @param fileName* @param response*/public static void excel2Pdf(InputStream inputStream,String fileName, HttpServletResponse response) {System.out.println("pdf转换中...");long old = System.currentTimeMillis();try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {// 验证if (!getLicense()) {throw new RuntimeException("文件转换失败!");}// 设置字体包位置IndividualFontConfigs configs = new IndividualFontConfigs();configs.setFontFolder("C:\\Windows\\Fonts", true);LoadOptions loadOptions = new LoadOptions();loadOptions.setFontConfigs(configs);// 也可以直接指定路径 workbook = new Workbook(docPath, loadOptions);Workbook workbook = new Workbook(inputStream, loadOptions);PdfSaveOptions opts = new PdfSaveOptions();// 设置excel不换行在pdf显示// opts.setAllColumnsInOnePagePerSheet(true);// 设置一个sheet在一页pdfopts.setOnePagePerSheet(true);workbook.save(fos, opts);response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));byte[] buffer = fos.toByteArray();InputStream arrayInputStream = new ByteArrayInputStream(buffer);byte[] buf = new byte[4096];int len = -1;while ((len = arrayInputStream.read(buf)) != -1) {response.getOutputStream().write(buf, 0, len);}long now = System.currentTimeMillis();System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");} catch (Exception e) {e.printStackTrace();throw new RuntimeException("文件转换失败!");} finally {try {if (inputStream != null) {inputStream.close();}} catch (IOException e) {e.printStackTrace();}}}
}

Controller实现:

@RestController
@RequestMapping("/test")
public class TestController {/*** 导入excel文件** @param file* @return* @throws Exception*/@RequestMapping("/excel")@ResponseBodypublic void uploadExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {if (file.isEmpty()) {return;}String originalFilename = file.getOriginalFilename();String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));Excel2PdfUtil.excel2Pdf(file.getInputStream(), fileName, response);}
}

postMan测试:
请求接口,比如:http://127.0.0.1:9090/test/excel

Java-Aspose实现上传Excel、Word转换为PDF并进行下载相关推荐

  1. Office文档上传后实时转换为PDF格式_图片文件上传后实时裁剪_实现在线预览Office文档

    Office文档上传后实时转换为PDF格式_图片文件上传后实时裁剪 前置条件 安装LibreOffice 安装OpenOffice 安装Unoconv 安装ImageMagick.x86_64 安装G ...

  2. 手机上怎么把Word转换为PDF

    大家经常会需要将Word文档转换为PDF的,电脑上也有很多的在线转换工具,当然如果你使用的是Word2017以上的版本也是可以直接另存为PDF格式的,但是要是电脑不在身边.或者是下班时间呢?其实Wor ...

  3. 学习java通过poi上传excel文件

    近期接了一个小功能,需要用到excel导入导出功能,学习了一下apache的poi技术,现做如下笔记: 传统的通过form表单提交上传文件的写法: <form action="XXX& ...

  4. 文件上传 java 完美,vue+java实现文件上传(excel等),会出现跨域问题,直接用form表单提交就不会有问题了(new FormData())...

    vue+java实现文件上传(excel等),会出现跨域问题,直接用form表单提交就不会有问题了(new FormData()) 地址:https://www.cnblogs.com/muscles ...

  5. 上传excel文件,导出excel模板实现

    此功能上商品导入,分别有导入组别,品类,属性(json字符串截取)等多功能多表实现. 导出功能,根据自定义需要的模板名称生成可配置模板 controller调用前段路径,然后导入/导出模板工具,ser ...

  6. C# office word转换为pdf

    using Word = Microsoft.Office.Interop.Word;/// <summary>/// office word转化为pdf/// </summary& ...

  7. java上传excel以及解析

    一.前言 在写管理后台的需求的时候,经常会用到上传excel的功能,需要我们解析Excel的内容,导入数据等. 二.上传 上传到文件服务器,文件服务有相关的上传接口,需要我们调用API上传. @Pos ...

  8. java ajax 导入excel_通过ajax上传excel

    搜索热词 html: @H_404_3@ @H_404_3@上       传:@H_404_3@ @H_404_3@ @H_404_3@ @H_404_3@ @H_404_3@导入@H_404_3@ ...

  9. java 文件上传Excel解析(表头不固定顺序,多sheet页)并插入数据库

    文件上传返回存贮路径 /** * 前端上传文件 返回存储路径 * */public static String fileUpload(HttpServletRequest request, HttpS ...

  10. java多附件上传 实例demo

    java多附件上传 实例demo <%@ page language="java" import="java.util.*" pageEncoding=& ...

最新文章

  1. 大佬原创 | 深度学习60讲453页pdf下载
  2. 开发者工具 Top 100 名单
  3. 常见的加密和解密算法—MD5
  4. 漫画:什么是时间复杂度
  5. Python callable 函数 - Python零基础入门教程
  6. pyinstaller 打包exe可执行文件
  7. unity3d 动态合批设置_【CocosCreator】突破动态合图
  8. linux vi代码高亮,linux Vi编辑器代码高亮设置及永久显示行号的方法
  9. 【二 HTTP编程】2. HTTP路由
  10. 如何正确的卸载MATLAB7?
  11. user-modify
  12. word2013免费版下载和安装
  13. QQ空间优化让百度收录你
  14. 2018-2-13-windows-10预览版升级win10-7月29-10240.16384
  15. Python真香之爬取古诗文网
  16. 双系统电脑如何将两个系统安装到一个分区
  17. linux使wifi进去低功耗,WiFi232低功耗系列模块加入路由器设置方法
  18. 高德 java.lang.UnsatisfiedLinkError: Native method not found: com.autonavi.amap.mapc
  19. 11月1日 迅雷白金会员vip账号分享 91freevip 上午10:00 更新
  20. 一个屌丝程序员的青春(一八六)

热门文章

  1. 8086c语言编译器,8086汇编语言编译器MKStudio安装使用教程
  2. Word转换PDF技巧之通过虚拟打印机生成pdf格式文件
  3. VisionPro实现测量工件内圆尺寸
  4. VB全局热键(快捷键)
  5. [Excel函数] 逻辑判断函数
  6. python面板数据模型_面板数据模型选择
  7. 【linux】X Server / X Client / Window manager 的关系
  8. windows常用网络命令
  9. 金山云服务器e1型,金山云-文档中心-重装系统
  10. 必应图片搜索——产品分析