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

2024-05-11 00:29

本文主要是介绍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);}}}

小姐姐

在这里插入图片描述

这篇关于20240510每日后端---聊聊文件预览,doc,image,ppt转PDF预览的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/977992

相关文章

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Python实现pdf电子发票信息提取到excel表格

《Python实现pdf电子发票信息提取到excel表格》这篇文章主要为大家详细介绍了如何使用Python实现pdf电子发票信息提取并保存到excel表格,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录应用场景详细代码步骤总结优化应用场景电子发票信息提取系统主要应用于以下场景:企业财务部门:需

Python对PDF书签进行添加,修改提取和删除操作

《Python对PDF书签进行添加,修改提取和删除操作》PDF书签是PDF文件中的导航工具,通常包含一个标题和一个跳转位置,本教程将详细介绍如何使用Python对PDF文件中的书签进行操作... 目录简介使用工具python 向 PDF 添加书签添加书签添加嵌套书签Python 修改 PDF 书签Pytho

SpringBoot后端实现小程序微信登录功能实现

《SpringBoot后端实现小程序微信登录功能实现》微信小程序登录是开发者通过微信提供的身份验证机制,获取用户唯一标识(openid)和会话密钥(session_key)的过程,这篇文章给大家介绍S... 目录SpringBoot实现微信小程序登录简介SpringBoot后端实现微信登录SpringBoo

使用Python自动化生成PPT并结合LLM生成内容的代码解析

《使用Python自动化生成PPT并结合LLM生成内容的代码解析》PowerPoint是常用的文档工具,但手动设计和排版耗时耗力,本文将展示如何通过Python自动化提取PPT样式并生成新PPT,同时... 目录核心代码解析1. 提取 PPT 样式到 jsON关键步骤:代码片段:2. 应用 JSON 样式到

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

在.NET平台使用C#为PDF添加各种类型的表单域的方法

《在.NET平台使用C#为PDF添加各种类型的表单域的方法》在日常办公系统开发中,涉及PDF处理相关的开发时,生成可填写的PDF表单是一种常见需求,与静态PDF不同,带有**表单域的文档支持用户直接在... 目录引言使用 PdfTextBoxField 添加文本输入域使用 PdfComboBoxField

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程