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 - A9
            percent = 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.mfbz.cn/a/611632.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

关于JAVA-JSP电子政务网实现参考论文(论文 + 源码)

【免费】关于JAVA-JSP电子政务网.zip资源-CSDN文库https://download.csdn.net/download/JW_559/89292355关于JAVA-JSP电子政务网 摘 要 当前阶段&#xff0c;伴随着社会信息技术的快速发展&#xff0c;使得电子政务能够成为我国政府职能部门进行办公管理的一个重要内容&#x…

代码随想录算法训练营第36期DAY24

DAY24 235二叉搜索树的最近公共祖先 迭代法&#xff1a; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solutio…

ssrf(第二弹)

四&#xff0c;post请求 1.打开环境&#xff0c;提示说发一个HTTP POST请求&#xff0c;ssrf是用php的curl实现的.并且会跟踪302跳转。 2.用dirsearch扫一下常见的端口&#xff0c;看到有三个可以访问的页面 3.构造伪协议&#xff0c;因为要通过172.0.0.1访问&#xff0c;我们…

在centos7中运行向量数据库PostgreSQL连接不上如何排查?

1. 检查 PostgreSQL 服务状态 首先&#xff0c;您需要确认 PostgreSQL 服务是否正在运行。您可以使用以下命令来检查服务状态&#xff1a; sudo systemctl status postgresql如果服务没有运行&#xff0c;您需要启动它&#xff1a; sudo systemctl start postgresql2. 确认 …

锚索测力计在岩土工程中的应用

随着现代工程建设的快速发展&#xff0c;岩土工程安全问题日益受到人们的关注。岩土工程中的锚索结构&#xff0c;作为保证工程稳定和安全的关键部分&#xff0c;其性能监测和评估显得尤为重要。近年来&#xff0c;锚索测力计作为一种先进的监测工具&#xff0c;在岩土工程安全…

粗俗理解多层感知器

一、前言 参考资料和图片均来自以下链接&#xff1a;https://www.youtube.com/watch?vaircAruvnKk&listPLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pihttps://www.youtube.com/watch?vbfmFfD2RIcghttps://www.youtube.com/watch?vKuXjwB4LzSAhttps://www.youtube.com/watch?vIl…

2024数维杯数学建模竞赛A题完整代码和思路论文解析

2024数维杯数学建模完整代码和成品论文已更新&#xff0c;获取↓↓↓↓↓ https://www.yuque.com/u42168770/qv6z0d/bgic2nbxs2h41pvt?singleDoc# 2024数维杯数学建模A题34页论文已完成&#xff0c;论文包括摘要、问题重述、问题分析、模型假设、符号说明、模型的建立和求解&…

linux下使用jexus部署aspnet站点

1.运行环境 Centos 7 安装dos2unix工具 yum install dos2unix 安装jexus curl https://jexus.org/release/x64/install.sh|sudo sh2.网站部署 2.1. 将windows下的网站发布包Msc_qingdao_admin.zip上传到linux中&#xff0c; 然后解压后放入/var/www(没有则创建)目录下 r…

ICode国际青少年编程竞赛- Python-4级训练场-绿色能量1

ICode国际青少年编程竞赛- Python-4级训练场-绿色能量1 1、 Dev.step(3) Dev.turnLeft() Dev.step(3) Spaceship.step(4) Spaceship.turnRight() Spaceship.step(4) Dev.step(3) while Item[1].y ! Dev.y:wait()2、 Dev.step(4) while Item[0].x ! Dev.x:wait() Dev.turnLe…

AScript纯本地离线文字识别插件

目的 AScript是一款可以模拟鼠标和键盘操作的自动化工具。它可以帮助用户自动完成一些重复的、繁琐的任务&#xff0c;节省大量人工操作的时间。但按键精灵是不包含图色功能&#xff0c;无法识别屏幕上的图像&#xff0c;根据图像的变化自动执行相应的操作。本篇文章主要讲解下…

15 华三华为链路聚合综述

1 链路聚合简介 以太网链路聚合通过将多条以太网物理链路捆绑在一起形成一条以太网逻辑链路&#xff0c;实现增加链路带宽的目的&#xff0c;同时这些捆绑在一起的链路通过相互动态备份&#xff0c;可以有效地提高链路的可靠性。 2 成员端口的状态 聚合组内的成员端口具有以下…

深入理解Docker容器镜像

深入理解Docker容器镜像 1 容器是什么&#xff1a;特殊的进程 容器其实是一种沙盒技术。顾名思义&#xff0c;沙盒就是能够像一个集装箱一样&#xff0c;把你的应用“装”起来的技术。这样&#xff0c;应用与应用之间&#xff0c;就因为有了边界而不至于相互干扰&#xff1b;而…

聊天室项目思路

发起群聊&#xff1a; 从好友表选取人发送到服务器&#xff0c;服务器随机生成不重复的群号&#xff0c;存储在数据库&#xff0c;同时建立中间表&#xff0c;处理用户与群聊的关系 申请入群&#xff1a; 输入群号&#xff0c;发消息给服务器&#xff0c;服务器查询是否存在…

如何使用openEuler 22.03 配置mail.rc给邮箱发送邮件

目录 需求环境总体步骤梳理详细步骤1. 安装mailx软件包&#xff08;centos默认安装&#xff0c;openEuler不默认安装&#xff09;2. 检查是否能ping得到smtp服务器3. 在qq邮箱开启smtp设置4. 修改/etc/mail.rc文件5. 测试 可能遇到的问题 需求 希望检查每日的备份和系统运行记…

[MRCTF2020]Ez_bypass1 and [网鼎杯 2020 青龙组]AreUSerialz1()php语言基础学习,以及序列化概念的基本了解

1.[MRCTF2020]Ez_bypass1 &#xff08;1&#xff09;打开环境后它是一串很长并且看起来非常混乱的代码&#xff0c;看不懂那咱就先不管&#xff0c;直接查看源码 &#xff08;2&#xff09;看了之后可以发现它涉及到很多东西 首先就是要进行一个仔细的代码审计&#xff0c;分…

代码随想录算法训练营第六十三天|84.柱状图中最大的矩形

代码随想录算法训练营第六十三天|84.柱状图中最大的矩形 84.柱状图中最大的矩形 给定 n 个非负整数&#xff0c;用来表示柱状图中各个柱子的高度。每个柱子彼此相邻&#xff0c;且宽度为 1 。 求在该柱状图中&#xff0c;能够勾勒出来的矩形的最大面积。 示例 1: 输入&…

调试代码问题汇总

1.最常见的就是数据库密码不对。根据调试视频将你的数据库密码设置正确&#xff0c;数据库密码是数字的优先直接连如果不成功可以加个双引号或者单引号。 提示&#xff1a;java.sql.SQLException: Access denied for user rootlocalhost (using password: YES) 2.原本配置好的…

我觉得POC应该贴近实际

今天我看到一位老师给我一份测试数据。 这是三个国产数据库。算是分布式的。其中有两个和我比较熟悉&#xff0c;但是这个数据看上去并不好。看上去第一个黄色的数据库数据是这里最好的了。但是即使如此&#xff0c;我相信大部分做数据库的人都知道。MySQL和PostgreSQL平时拿出…

【算法基础实验】排序-最小优先队列MinPQ

优先队列 理论知识 MinPQ&#xff08;最小优先队列&#xff09;是一种常见的数据结构&#xff0c;用于有效管理一组元素&#xff0c;其中最小元素可以快速被检索和删除。这种数据结构广泛应用于各种算法中&#xff0c;包括图算法&#xff08;如 Dijkstra 的最短路径算法和 Pr…

RISCV 外部GCC 工具链安装@FreeBSD15

在交叉编译的时候&#xff0c;可以使用FreeBSD15默认的工具链&#xff1a;LLVM 也可以使用GCC工具链&#xff0c;GCC可以使用现成pkg包安装&#xff0c;也可以编译安装。 LLVM的特点是高移植性和高效&#xff0c;但学习成本高。GCC的特点是成熟稳定&#xff0c;但优化能力有限…
最新文章