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表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

Java使用Spire.Doc for Java实现Word自动化插入图片

《Java使用Spire.DocforJava实现Word自动化插入图片》在日常工作中,Word文档是不可或缺的工具,而图片作为信息传达的重要载体,其在文档中的插入与布局显得尤为关键,下面我们就来... 目录1. Spire.Doc for Java库介绍与安装2. 使用特定的环绕方式插入图片3. 在指定位

Java利用Spire.Doc for Java实现在模板的基础上创建Word文档

《Java利用Spire.DocforJava实现在模板的基础上创建Word文档》在日常开发中,我们经常需要根据特定数据动态生成Word文档,本文将深入探讨如何利用强大的Java库Spire.Do... 目录1. Spire.Doc for Java 库介绍与安装特点与优势Maven 依赖配置2. 通过替换

Python结合Free Spire.PDF for Python实现PDF页面旋转

《Python结合FreeSpire.PDFforPython实现PDF页面旋转》在日常办公或文档处理中,我们经常会遇到PDF页面方向错误的问题,本文将分享如何用Python结合FreeSpir... 目录基础实现:单页PDF精准旋转完整代码代码解析进阶操作:覆盖多场景旋转需求1. 旋转指定角度(90/27

使用C#实现将RTF转换为PDF

《使用C#实现将RTF转换为PDF》RTF(RichTextFormat)是一种通用的文档格式,允许用户在不同的文字处理软件中保存和交换格式化文本,下面我们就来看看如何使用C#实现将RTF转换为PDF... 目录Spire.Doc for .NET 简介安装 Spire.Doc代码示例处理异常总结RTF(R

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

使用Python在PDF中绘制多种图形的操作示例

《使用Python在PDF中绘制多种图形的操作示例》在进行PDF自动化处理时,人们往往首先想到的是文本生成、图片嵌入或表格绘制等常规需求,然而在许多实际业务场景中,能够在PDF中灵活绘制图形同样至关重... 目录1. 环境准备2. 创建 PDF 文档与页面3. 在 PDF 中绘制不同类型的图形python

使用Python实现在PDF中添加、导入、复制、移动与删除页面

《使用Python实现在PDF中添加、导入、复制、移动与删除页面》在日常办公和自动化任务中,我们经常需要对PDF文件进行页面级的编辑,使用Python,你可以轻松实现这些操作,而无需依赖AdobeAc... 目录1. 向 PDF 添加空白页2. 从另一个 PDF 导入页面3. 删除 PDF 中的页面4. 在

C#自动化生成PowerPoint(PPT)演示文稿

《C#自动化生成PowerPoint(PPT)演示文稿》在当今快节奏的商业环境中,演示文稿是信息传递和沟通的关键工具,下面我们就深入探讨如何利用C#和Spire.Presentationfor.NET... 目录环境准备与Spire.Presentation安装核心操作:添加与编辑幻灯片元素添加幻灯片文本操

OFD格式文件及如何适应Python将PDF转换为OFD格式文件

《OFD格式文件及如何适应Python将PDF转换为OFD格式文件》OFD是中国自主研发的一种固定版式文档格式,主要用于电子公文、档案管理等领域,:本文主要介绍OFD格式文件及如何适应Python... 目录前言什么是OFD格式文档?使用python easyofd库将PDF转换为OFD第一步:安装 eas