20240510每日后端---聊聊文件预览,doc,image,ppt转PDF预览

一、引入依赖

    <dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>15.8</version></dependency><dependency><groupId>com.aspose</groupId><artifactId>cracked</artifactId><version>21.8</version></dependency>

二、引入工具类

import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.xslf.usermodel.*;

import java.awt.;
import java.awt.image.BufferedImage;
import java.io.
;
import java.util.List;

public class PreviewUtil {

/*** @param inputStream  源文件输入流* @param outputStream pdf文件输出流**/
public static boolean imgToPdf(InputStream inputStream, OutputStream outputStream) {Document document = null;try {// 创建文档,设置PDF页面的大小 A2-A9, 个人觉得A3最合适document = new Document(PageSize.A3, 20, 20, 20, 20);// 新建pdf文档,具体逻辑看.getInstance方法PdfWriter.getInstance(document, outputStream);document.open();document.newPage();// 将文件流转换为字节流,便于格式转换BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] bytes = new byte[1024];int length = 0 ;while (-1 != (length = bufferedInputStream.read(bytes))) {byteArrayOutputStream.write(bytes, 0, length);}// 处理img图片Image image = Image.getInstance(byteArrayOutputStream.toByteArray());float height = image.getHeight();float width = image.getWidth();float percent = 0.0f;// 设置像素或者长宽高,将会影响图片的清晰度,因为只是对图片放大或缩小if (height > width) {// A4 - A9percent = PageSize.A6.getHeight() / height * 100;} else {percent = PageSize.A6.getWidth() / width * 100;}image.setAlignment(Image.MIDDLE);image.scalePercent(percent);// 将图片放入文档中,完成pdf转换document.add(image);} catch (Exception e) {e.printStackTrace();return false;} finally {try {if (document != null) {document.close();}} catch (Exception e) {e.printStackTrace();}}return true;
}/*** @param inputStream  源文件输入流* @param outputStream pdf文件输出流**/
public static boolean wordTopdfByAspose(InputStream inputStream, OutputStream outputStream) {// 验证License 若不验证则转化出的pdf文档会有水印产生if (!getLicense()) {return false;}try {// 将源文件保存在com.aspose.words.Document中,具体的转换格式依靠里面的save方法com.aspose.words.Document doc = new com.aspose.words.Document(inputStream);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换doc.save(outputStream, SaveFormat.PDF);System.out.println("word转换完毕");} catch (Exception e) {e.printStackTrace();return false;}finally {if (outputStream != null) {try {outputStream.flush();outputStream.close();} catch (IOException e) {e.printStackTrace();}}}return true;}// 官方文档的要求 无需理会
public static boolean getLicense() {boolean result = false;try {String s = "<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>";ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;
}/*** @param inputStream  源文件输入流* @param outputStream pdf文件输出流**/
public static boolean excelToPdf(InputStream inputStream, OutputStream outputStream) {// 验证License 若不验证则转化出的pdf文档会有水印产生if (!getExeclLicense()) {return false;}try {com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(inputStream);// 原始excel路径com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();pdfSaveOptions.setOnePagePerSheet(false);int[] autoDrawSheets={3};//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。autoDraw(wb,autoDrawSheets);int[] showSheets={0};//隐藏workbook中不需要的sheet页。printSheetPage(wb,showSheets);wb.save(outputStream, pdfSaveOptions);outputStream.flush();outputStream.close();System.out.println("excel转换完毕");} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return true;
}/*** 设置打印的sheet 自动拉伸比例* @param wb* @param page 自动拉伸的页的sheet数组*/
public static void autoDraw(com.aspose.cells.Workbook wb,int[] page){if(null!=page&&page.length>0){for (int i = 0; i < page.length; i++) {wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();wb.getWorksheets().get(i).getVerticalPageBreaks().clear();}}
}/*** 隐藏workbook中不需要的sheet页。** @param wb* @param page 显示页的sheet数组*/
public static void printSheetPage(com.aspose.cells.Workbook wb, int[] page) {for (int i = 1; i < wb.getWorksheets().getCount(); i++) {wb.getWorksheets().get(i).setVisible(false);}if (null == page || page.length == 0) {wb.getWorksheets().get(0).setVisible(true);} else {for (int i = 0; i < page.length; i++) {wb.getWorksheets().get(i).setVisible(true);}}
}public static boolean getExeclLicense() {boolean result = false;try {String s = "<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>";ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());com.aspose.cells.License aposeLic = new com.aspose.cells.License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;
}/***  pptxToPdf* @param inputStream* @param outputStream* @return*/
public static boolean pptxToPdf(InputStream inputStream, OutputStream outputStream) {Document document = null;XMLSlideShow slideShow = null;PdfWriter pdfWriter = null;try {slideShow = new XMLSlideShow(inputStream);Dimension dimension = slideShow.getPageSize();document = new Document();pdfWriter = PdfWriter.getInstance(document, outputStream);document.open();PdfPTable pdfPTable = new PdfPTable(1);List<XSLFSlide> slideList = slideShow.getSlides();for (int i = 0, row = slideList.size(); i < row; i++) {XSLFSlide slide = slideList.get(i);// 设置字体, 解决中文乱码for (XSLFShape shape : slide.getShapes()) {XSLFTextShape textShape = (XSLFTextShape) shape;for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {for (XSLFTextRun textRun : textParagraph.getTextRuns()) {textRun.setFontFamily("宋体");}}}BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);Graphics2D graphics2d = bufferedImage.createGraphics();graphics2d.setPaint(Color.white);graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));slide.draw(graphics2d);graphics2d.dispose();Image image = Image.getInstance(bufferedImage, null);image.scalePercent(50f);// 写入单元格pdfPTable.addCell(new PdfPCell(image, true));document.add(image);}} catch (Exception e) {e.printStackTrace();return false;} finally {if (document != null) {document.close();}if (pdfWriter != null) {pdfWriter.close();}}System.out.println("pptx转换完毕");return true;
}}

三、调用工具类

public void pdfPreview (@RequestParam("fileId") String fileId, HttpServletResponse response){SysFileInfo sysFileInfo = projectInfoService.getPdfByFileId(fileId);byte[] fileBytes = FileUtilsNew.getFileByteByUrl(sysFileInfo.getFileUrl());ByteArrayInputStream byteArrayInputStream = null;ByteArrayOutputStream byteArrayOutputStream=null;ByteArrayInputStream bais=null;BufferedInputStream bin=null;PdfReader reader=null;try {byteArrayInputStream=new ByteArrayInputStream(fileBytes);byteArrayOutputStream=new ByteArrayOutputStream();boolean needSwitchFlag=true;byte[] byteArray=new byte[1024];if (needSwitchFlag){String typeBig = sysFileInfo.getFileSuffix();if (typeBig.contains("doc")){PreviewUtil.wordTopdfByAspose(byteArrayInputStream, byteArrayOutputStream);}if (typeBig.contains("xls")){PreviewUtil.excelToPdf(byteArrayInputStream, byteArrayOutputStream);}String[] imgType = new String[]{"jpg", "png", "jpeg", "bmp"};//判断包含图片类型if (Arrays.asList(imgType).contains(typeBig)) {PreviewUtil.imgToPdf(byteArrayInputStream, byteArrayOutputStream);}String[] pptType = new String[]{"ppt", "pptx"};if (Arrays.asList(pptType).contains(typeBig)) {PreviewUtil.pptxToPdf(byteArrayInputStream, byteArrayOutputStream);}byteArray = byteArrayOutputStream.toByteArray();}else{byteArray=fileBytes;}response.setContentType("application/pdf;charset=utf-8");response.setCharacterEncoding(UTF_8);bais = new ByteArrayInputStream(byteArray);bin = new BufferedInputStream(bais);reader = new PdfReader(bin);PdfStamper stamper = new PdfStamper(reader,response.getOutputStream());PdfGState gs = new PdfGState();gs.setFillOpacity(1f);// 设置透明度stamper.close();}catch (Exception e){log.error("文件预览异常",e);}finally {try {if(byteArrayInputStream!=null){byteArrayInputStream.close();}}catch (Exception e){log.error("文件流关闭失败",e);}try {if(byteArrayOutputStream!=null){byteArrayOutputStream.close();}}catch (Exception e){log.error("文件流关闭失败",e);}try {if(bais!=null){bais.close();}}catch (Exception e){log.error("文件流关闭失败",e);}try {if(bin!=null){bin.close();}}catch (Exception e){log.error("文件流关闭失败",e);}try {if(reader!=null){reader.close();}}catch (Exception e){log.error("文件流关闭失败",e);}}}

小姐姐

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/686096.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

(十)JSP教程——config对象

config对象是脚本程序配置对象&#xff0c;表示当前JSP页面的配置信息。由于JSP页面通常无需配置&#xff0c;因此该对象在JSP页面中比较少见。 config对象可以读取一些初始化参数的值&#xff0c;而这些参数一般在web.xml配置文件中可以看到&#xff0c;并通过config对象的相应…

CTFHUB-技能树-Web题-RCE(远程代码执行)-文件包含

CTFHUB-技能树-Web题-RCE&#xff08;远程代码执行&#xff09; 文件包含 文章目录 CTFHUB-技能树-Web题-RCE&#xff08;远程代码执行&#xff09;文件包含解题方法1:![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/71f7355b3c124dfe8cdf1c95e6991553.png#pic_ce…

vue3对象数组格式的动态表单校验

如你有一个表单&#xff0c;表单内容是对象&#xff0c;但是对象内还有可动态循环的数组进行动态表单校验。 效果如图&#xff1a;查看源码 页面内容&#xff1a; <div class"arrForm-Box"><el-form :model"state.formData" :rules"rule…

day5Qt作业

服务器端 #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);//准备组件&#xff0c;初始化组件状态this->setFixedSize(800,600);chatwidget new QListWidge…

【系统架构师】-案例篇(七)信息安全

某软件公司拟开发一套信息安全支撑平台&#xff0c;为客户的局域网业务环境提供信息安全保护。该支撑平台的主要需求如下&#xff1a; 1.为局域网业务环境提供用户身份鉴别与资源访问授权功能&#xff1b; 2.为局域网环境中交换的网络数据提供加密保护&#xff1b; 3.为服务…

数据驱动实战二

目标 掌握数据驱动的开发流程掌握如何读取JSON数据文件巩固PO模式 1. 案例 对TPshop网站的登录模块进行单元测试 1.1 实现步骤 编写测试用例采用PO模式的分层思想对页面进行封装编写测试脚本定义数据文件&#xff0c;实现参数化 1.2 用例设计 1.3 数据文件 {"login…

LangChain连接国内大模型测试|智谱ai、讯飞星火、通义千问

智谱AI 配置参考 https://python.langchain.com/v0.1/docs/integrations/chat/zhipuai/ZHIPUAI_API_KEY从https://open.bigmodel.cn/获取 from langchain_community.chat_models import ChatZhipuAI from langchain_core.messages import AIMessage, HumanMessage, SystemMes…

【计算机毕业设计】springboot国风彩妆网站

二十一世纪我们的社会进入了信息时代&#xff0c; 信息管理系统的建立&#xff0c;大大提高了人们信息化水平。传统的管理方式对时间、地点的限制太多&#xff0c;而在线管理系统刚好能满足这些需求&#xff0c;在线管理系统突破了传统管理方式的局限性。于是本文针对这一需求设…

最新版在线客服系统源码

源码介绍 首发最新在线客服系统源码&#xff0c;优化更好并且重构源码布局UI 性能不吃cpu并发快,普通1H2G都能带动最新版只要是服务器都能带动 搭建即可使用,操作简单,易懂 修复了老版本bug 内附有搭建教程 gofly.v1kf.com 运行环境 Nginx 1.20 MySQL 5.7 演示截图

如何自动(定时/间隔/重复)执行 同步文件、备份打包加密压缩文件

参考下列两个教程结合使用即可&#xff1a; 快捷自由定时重启、注销、关机 如何从多个文件夹内转移全部文件&#xff08;忽略文件夹的结构&#xff09;&#xff08;进行复制&#xff09;&#xff08;再打包&#xff09; 就是先设定好 勾选对 来源路径’Zip打包&#xff0c;并…

Logstash分析MySQL慢查询日志实践

删除匹配到的行&#xff0c;当前行信息不记录到message中

ICRA 2024 成果介绍:基于 RRT* 的连续体机器人高效轨迹规划方法

近来&#xff0c;连续体机器人研究受到越来越多的关注。其灵活度高&#xff0c;可以调整形状适应动态环境&#xff0c;特别适合于微创手术、工业⽣产以及危险环境探索等应用。 连续体机器人拥有无限自由度&#xff08;DoF&#xff09;&#xff0c;为执行空间探索等任务提供了灵…