• java excel、word、PPT转换成pdf预览


    先引入包:[lib下载地址](https://mp.csdn.net/mp_download/manage/download/UpDetailed)
    
    • 1

    在这里插入图片描述
    在这里插入图片描述

    Controller
        public AjaxResult fileToPdf(@RequestBody VerifyCode url, HttpServletResponse response, HttpServletRequest request) throws IOException {
            String fileUrl = request.getScheme() + "://" + request.getServerName() + ":" + port + fileDir + url.getFileName().split("\\.")[0]+ ".pdf";
            String fileToPdfUrl = fileToPdf + url.getFileName().split("\\.")[0] + ".pdf";
            File newFile = new File(fileToPdfUrl);
            if(newFile.exists()){
                return AjaxResult.success(fileUrl);
            }
            File file = new File(fileToPdf);
            if(!file.exists()){
                file.mkdirs();
            }
            String suffix = url.getUrl().substring(url.getUrl().lastIndexOf("."));
            String type = FileTransForUtils.getResourceTypesDocument(suffix);
            if("word".equals(type)){
                return AjaxResult.success(FileTransForUtils.word3Pdf(url.getUrl(),response.getOutputStream(),fileToPdfUrl,fileUrl));
            }else if("excel".equals(type)){
                return AjaxResult.success(FileTransForUtils.excel3pdf(url.getUrl(), response.getOutputStream(),fileToPdfUrl,fileUrl));
            }else if("ppt".equals(type)){
                return AjaxResult.success(FileTransForUtils.ppt3pdf(url.getUrl(),response.getOutputStream(),fileToPdfUrl,fileUrl));
            }else {
                return AjaxResult.success(fileUrl);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    package com.det.utils;
    
    import com.aspose.cells.Workbook;
    import com.aspose.slides.Presentation;
    import com.aspose.words.Document;
    import com.aspose.words.License;
    import com.aspose.words.SaveFormat;
    import com.det.common.utils.file.FileUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    import java.io.*;
    import java.nio.charset.StandardCharsets;
    import java.rmi.ServerException;
    
    /**
     * @Author: lsx
     * @createDate: 2023/11/5 10:49
     * @description:
     */
    public class FileTransForUtils {
    
            private static final Logger logger = LoggerFactory.getLogger(FileTransForUtils.class);
            //word转PDF
            public synchronized static String word3Pdf(String wordPath, OutputStream outputStream,String fileName,String fileUrl) throws ServerException {
                if (!getLicense("word")) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
                    throw new ServerException("验证License失败。");
                }
                try {
                    long old = System.currentTimeMillis();
                    InputStream inputStreamFromUrl = FileUtils.getInputStreamFromUrl(wordPath);
                    //Address是将要被转化的word文档
                    Document doc = new Document(inputStreamFromUrl);
                    //新建一个pdf文档
                    File file = new File(fileName);
                    FileOutputStream os = new FileOutputStream(file);
                    //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,
    //                doc.save(outputStream, SaveFormat.PDF);
                    doc.save(os, SaveFormat.PDF);
                    // XPS, SWF 相互转换
                    long now = System.currentTimeMillis();
                    os.close();
                    outputStream.flush();
                    outputStream.close();
                    logger.info("word共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
                } catch (Exception e) {
                    logger.error(String.valueOf(e));
                    e.printStackTrace();
                }
                return fileUrl;
            }
            //excel转PDF
            public synchronized static String excel3pdf(String excelPath, OutputStream outputStream,String fileName,String fileUrl) throws ServerException {
                if (!getLicense("excel")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
                    throw new ServerException("验证License失败。");
                }
                try {
                    long old = System.currentTimeMillis();
                    InputStream inputStreamFromUrl = FileUtils.getInputStreamFromUrl(excelPath);
                    Workbook wb = new Workbook(inputStreamFromUrl);// 原始excel路径
                    //新建一个pdf文档
                    File file = new File(fileName);
                    FileOutputStream os = new FileOutputStream(file);
    //                wb.save(outputStream,com.aspose.cells.SaveFormat.PDF);
                    wb.save(os,com.aspose.cells.SaveFormat.PDF);
                    long now = System.currentTimeMillis();
                    outputStream.flush();
                    outputStream.close();
                    os.close();
                    logger.info("excel共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
                } catch (Exception e) {
                    logger.error(String.valueOf(e));
                    e.printStackTrace();
                }
                return fileUrl;
            }
            //ppt转PDF
            public synchronized static String ppt3pdf(String pptPath, OutputStream outputStream,String fileName,String fileUrl) throws ServerException {
                // 验证License
                if (!getLicense("ppt")) {
                    throw new ServerException("验证License失败。");
                }
                FileOutputStream os = null;
                try {
                    long old = System.currentTimeMillis();
                    InputStream inputStreamFromUrl = FileUtils.getInputStreamFromUrl(pptPath);
                    Presentation pres = new Presentation(inputStreamFromUrl);//输入ppt路径
                    //IFontsManager fontsManager = pres.getFontsManager();
                    //新建一个pdf文档
                    File file = new File(fileName);
                    os = new FileOutputStream(file);
    //                pres.save(outputStream,com.aspose.slides.SaveFormat.Pdf);
                    pres.save(os,com.aspose.slides.SaveFormat.Pdf);
                    outputStream.flush();
                    outputStream.close();
                    long now = System.currentTimeMillis();
                    logger.info("ppt共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
                } catch (Exception e) {
                    logger.error(String.valueOf(e));
                    e.printStackTrace();
                }finally {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return fileUrl;
            }
            //剔除水印
            private static boolean getLicense(String type) {
                boolean result = false;
                try {
                    // 凭证
                    String license =
                            "\n" +
                                    "  \n" +
                                    "    \n" +
                                    "      Aspose.Total for Java\n" +
                                    "      Aspose.Words for Java\n" +
                                    "    \n" +
                                    "    Enterprise\n" +
                                    "    20991231\n" +
                                    "    20991231\n" +
                                    "    8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7\n" +
                                    "  \n" +
                                    "  sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=\n" +
                                    "";
                    InputStream is = new ByteArrayInputStream(license.getBytes(StandardCharsets.UTF_8));
                    if(type.equals("word")){
                        License asposeLic = new License();
                        asposeLic.setLicense(is);
                    }else if (type.equals("excel")){
                        com.aspose.cells.License asposeLic = new com.aspose.cells.License();
                        asposeLic.setLicense(is);
                    }else if (type.equals("ppt")){
                        com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                        aposeLic.setLicense(is);
                    }
                    result = true;
                } catch (Exception e) {
                    logger.error(String.valueOf(e));
                    e.printStackTrace();
                    return false;
                }
                return result;
            }
            /**
             * 判断资源类型文档类
             */
            public static String getResourceTypesDocument(String suffix) {
                String type = null;
                switch (suffix) {
                    //文档类型
                    case ".doc":
                    case ".docx":
                    case ".txt":
                        type = "word";
                        break;
                    case ".xls":
                    case ".xlsx":
                        type = "excel";
                        break;
                    case ".ppt":
                    case ".pptx":
                        type = "ppt";
                        break;
                }
                return type;
            }
    
            public static void main(String[] args) throws FileNotFoundException {
                String inputPath = "C:\\Users\\detong\\Desktop\\安全活动记录.docx";
    //            String outputPath = "C:\\Users\\detong\\Desktop\\焊工作业教育培训2023.pdf";
                String suffix = inputPath.substring(inputPath.lastIndexOf("."));
                String type = getResourceTypesDocument(suffix);
                /*if("word".equals(type)){
                    word3Pdf(inputPath,new FileOutputStream(new File("C:\\Users\\detong\\Desktop\\安全活动记录.word")));
                }else if("excel".equals(type)){
                    excel3pdf(inputPath,new FileOutputStream(new File("C:\\Users\\detong\\Desktop\\安全活动记录.excel")));
                }else if("ppt".equals(type)){
                    ppt3pdf(inputPath,new FileOutputStream(new File("C:\\Users\\detong\\Desktop\\安全活动记录.pdf")));
                }*/
            }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
  • 相关阅读:
    静图表情包怎么做成动态图?动图表情包制作教程
    【CesiumforUnreal插件】UE5 快速构建Cesium场景 快速入门!!!
    驱动开发:内核实现进程汇编与反汇编
    Windows Server 2012 R2系统 修改远程登陆密码
    已解决ValueError: If using all scalar values, you must pass an index
    LSF_SPAN
    【学习笔记】快速幂
    Spring Security详细学习第二篇(授权,异常处理,跨域)
    List Set Map Queue Deque 之间的区别是什么?
    Linux查看程序和动态库依赖的动态库
  • 原文地址:https://blog.csdn.net/qq_39994174/article/details/134307807