700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【SpringBoot】40 SpringBoot中使用Aspose将文件转为PDF实现预览

【SpringBoot】40 SpringBoot中使用Aspose将文件转为PDF实现预览

时间:2018-07-28 01:21:35

相关推荐

【SpringBoot】40 SpringBoot中使用Aspose将文件转为PDF实现预览

一、简介

Aspose 是 .NET 和 Java 开发组件以及为 Microsoft SQL Server Reporting Services 和 JasperReports 等平台提供渲染扩展的领先供应商。它的核心重点是提供最完整和最强大的文件管理产品。Aspose 产品支持一些商业上最流行的文件格式,包括:Word 文档、Excel 电子表格、PowerPoint 演示文稿、PDF 文档、Flash 演示文稿和项目文件。

二、下载

下载 Aspose 的依赖 Jar 包可以通过一下仓库下载:Aspose 依赖下载

/repo/com/aspose/

本次我们需要使用的 Jar 包如下:

1、aspose-words,word 转 pdf 使用2、aspose-cells,excel 转 pdf 使用3、aspose-slides,ppt 转 pdf 使用

三、整合 Aspose

1、将下载下来的 Jar 包依赖放在 resources/lib/ 目录下

2、pom.xml 文件引入

<!-- 转化pdf start --><dependency><groupId>aspose-words</groupId><artifactId>aspose-words</artifactId><version>15.8.0</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath></dependency><dependency><groupId>aspose-cells</groupId><artifactId>aspose-cells</artifactId><version>8.8.0</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.8.0.jar</systemPath></dependency><dependency><groupId>aspose-slides</groupId><artifactId>aspose-slides</artifactId><version>20.4</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-slides-20.4-jdk16.jar</systemPath></dependency><!-- 转化pdf end -->

四、自定义工具类

我们将转化的方法放在一个工具类中,PdfUtils.java,内容如下:

package mon.office;import com.aspose.cells.Workbook;import com.aspose.slides.Presentation;import com.aspose.words.Document;import java.io.*;import .HttpURLConnection;import .URL;import java.util.UUID;/*** 文件转PDF* <p>* Aspose下载地址:/repo/com/aspose/*/public class PdfUtils {/*** word 转为 pdf 输出** @param inPath word文件* @param outPath pdf 输出文件目录*/public static String word2pdf(String inPath, String outPath) {// 验证Licenseif (!isWordLicense()) {return null;}FileOutputStream os = null;try {String path = outPath.substring(0, outPath.lastIndexOf(File.separator));File file = new File(path);// 创建文件夹if (!file.exists()) {file.mkdirs();}// 新建一个空白pdf文档file = new File(outPath);os = new FileOutputStream(file);// Address是将要被转化的word文档Document doc = new Document(inPath);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,doc.save(os, com.aspose.words.SaveFormat.PDF);os.close();} catch (Exception e) {if (os != null) {try {os.close();} catch (IOException e1) {e1.printStackTrace();}}e.printStackTrace();}return outPath;}/*** excel 转为 pdf 输出** @param inPath excel 文件* @param outPath pdf 输出文件目录*/public static String excel2pdf(String inPath, String outPath) {// 验证Licenseif (!isWordLicense()) {return null;}FileOutputStream os = null;try {String path = outPath.substring(0, outPath.lastIndexOf(File.separator));File file = new File(path);// 创建文件夹if (!file.exists()) {file.mkdirs();}// 新建一个空白pdf文档file = new File(outPath);os = new FileOutputStream(file);// Address是将要被转化的excel表格Workbook workbook = new Workbook(new FileInputStream(getFile(inPath)));workbook.save(os, com.aspose.cells.SaveFormat.PDF);os.close();} catch (Exception e) {if (os != null) {try {os.close();} catch (IOException e1) {e1.printStackTrace();}}e.printStackTrace();}return outPath;}/*** ppt 转为 pdf 输出** @param inPath ppt 文件* @param outPath pdf 输出文件目录*/public static String ppt2pdf(String inPath, String outPath) {// 验证Licenseif (!isWordLicense()) {return null;}FileOutputStream os = null;try {String path = outPath.substring(0, outPath.lastIndexOf(File.separator));File file = new File(path);// 创建文件夹if (!file.exists()) {file.mkdirs();}// 新建一个空白pdf文档file = new File(outPath);os = new FileOutputStream(file);// Address是将要被转化的PPT幻灯片Presentation pres = new Presentation(new FileInputStream(getFile(inPath)));pres.save(os, com.aspose.slides.SaveFormat.Pdf);os.close();} catch (Exception e) {if (os != null) {try {os.close();} catch (IOException e1) {e1.printStackTrace();}}e.printStackTrace();}return outPath;}/*** 验证 Aspose.word 组件是否授权* 无授权的文件有水印和试用标记*/public static boolean isWordLicense() {boolean result = false;try {// 避免文件遗漏String licensexml = "<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 inputStream = new ByteArrayInputStream(licensexml.getBytes());com.aspose.words.License license = new com.aspose.words.License();license.setLicense(inputStream);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** OutputStream 转 InputStream*/public static ByteArrayInputStream parse(OutputStream out) {ByteArrayOutputStream baos = (ByteArrayOutputStream) out;ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());return swapStream;}/*** InputStream 转 File*/public static File inputStreamToFile(InputStream ins, String name) throws Exception {File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);if (file.exists()) {return file;}OutputStream os = new FileOutputStream(file);int bytesRead;int len = 8192;byte[] buffer = new byte[len];while ((bytesRead = ins.read(buffer, 0, len)) != -1) {os.write(buffer, 0, bytesRead);}os.close();ins.close();return file;}/*** 根据网络地址获取 File 对象*/public static File getFile(String url) throws Exception {String suffix = url.substring(url.lastIndexOf("."));HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();httpUrl.connect();return PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + suffix);}}

1、我们需要通过 isWordLicense() 方法验证 Aspose.word 组件是否授权,如果未授权,转化出来的文件会带有水印和使用标记,影响阅读,因为 Aspose.word 是一个商用版本,目前 word 转 pdf 正常,excel 转 pdf 会带有水印但不影响阅读,ppt 转 pdf 会有严重水印,影响阅读2、根据自定义的 pdf 输出目录,新建一个空白的 pdf 文件,然后将空白的 pdf 文件转化为 文件输出流 FileOutputStream3、Document doc = new Document(inPath);,doc 就是将要被转化的 word 文档4、doc.save(os, com.aspose.words.SaveFormat.PDF);,将转化的 word 文档写入空白的 pdf 文件中,就得到了我们的 pdf 文件5、os.close();,别忘记关闭输出流噢6、excel,ppt 的转化原理也是一致

五、测试

我们通过 API 的形式来,测试能不能将文件抓为 PDF 文件实现在线预览

1、开放 API

package com.asurplus.api.controller;import mon.office.PdfUtils;import io.swagger.annotations.Api;import mons.lang3.StringUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import .HttpURLConnection;import .URL;import java.util.UUID;/*** 在线office预览** @Author admin**/@Api(tags = "在线office预览")@Controller@RequestMapping("api/office")public class OfficeApiController {@GetMapping("previewPdf")public void pdf(String url, HttpServletResponse response) throws Exception {if (StringUtils.isBlank(url)) {return;}File file = null;// 文件后缀String suffix = url.substring(url.lastIndexOf(".") + 1);// 如果是PDFif ("pdf".equals(suffix)) {HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();httpUrl.connect();file = PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + ".pdf");response.setContentType("application/pdf");}// 如果是文本else if ("txt".equals(suffix)) {HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();httpUrl.connect();file = PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + ".txt");response.setContentType("text/html");}// 如果是docelse if ("doc".equals(suffix) || "docx".equals(suffix)) {file = new File(PdfUtils.word2pdf(url, System.getProperty("user.dir") + UUID.randomUUID().toString() + ".pdf"));response.setContentType("application/pdf");}// 如果是excelelse if ("xls".equals(suffix) || "xlsx".equals(suffix)) {file = new File(PdfUtils.excel2pdf(url, System.getProperty("user.dir") + UUID.randomUUID().toString() + ".pdf"));response.setContentType("application/pdf");}// 如果是pptelse if ("ppt".equals(suffix) || "pptx".equals(suffix)) {file = new File(PdfUtils.ppt2pdf(url, System.getProperty("user.dir") + UUID.randomUUID().toString() + ".pdf"));response.setContentType("application/pdf");}// 如果文件为空if (null == file) {return;}try {response.setCharacterEncoding("UTF-8");InputStream stream = new FileInputStream(file);ServletOutputStream out = response.getOutputStream();byte buff[] = new byte[1024];int length = 0;while ((length = stream.read(buff)) > 0) {out.write(buff, 0, length);}stream.close();out.close();out.flush();} catch (IOException e) {e.printStackTrace();}}}

我们需要传入需要转化的文件的在线地址,通过 Aspose 将文件转化为 PDF 文件输出到页面,实现在线预览

2、测试

准备一个 word 文件,内容如下:

在线转化后:

通过访问 API,成功将 word 文件转化为 pdf 文件,实现了在线预览

如您在阅读中发现不足,欢迎留言!!!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。