服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot实现PPT格式文件上传并在线预览功能

SpringBoot实现PPT格式文件上传并在线预览功能

2022-07-19 10:38Just do Java Java教程

本文介绍SpringBoot实现PPT格式文件上传并在线预览功能,通过上传接口,可在C盘的tempfile目录下找到上传的文件,预览时会在同级目录下创建一个相同文件名后缀为pdf的文件,每次预览会先查找文件是否存在,存在则直接预览,不存

1、需要引入依赖

?
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
<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.9</version>
        </dependency>
         <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
               <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
        <!--其他格式转换为PDF -->
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>xdocreport</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

2、上传文件到本地文件夹中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
   public ResponseEntity<Object> uploadFileToLocal(@RequestParam("multipartFile") MultipartFile multipartFile) {
       if (multipartFile == null) {
           return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
       }
       File file = null;
       try {
           File dir = new File(basePath);
           if (!dir.exists()) {
               dir.mkdir();
           }
           file = new File(basePath + File.separator + multipartFile.getOriginalFilename());
           if (!file.exists()) {
               multipartFile.transferTo(file);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
       return ResponseEntity.ok(FileVo.builder().size(multipartFile.getSize()).path(file.getAbsolutePath()).build());
 
   }

basePath为定义的常量: private static final String basePath = “C:\tempFile”;

通过上传接口,可在C盘的tempfile目录下找到上传的文件,首先我们先上传一个PPT文件,上传成功会返回文件的绝对路径地址以及文件大小,绝对地址将作为在线预览文件接口的参数。

3、在线预览PPT文件

?
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
@GetMapping("/showPPT")
   public void showPPT(@RequestParam("path") String path,HttpServletResponse response) throws IOException {
       byte[] buffer = new byte[1024 * 4];
       String type = path.substring(path.lastIndexOf(".") + 1);
       //转换pdf文件,如存在则直接显示pdf文件
       String pdf = path.replace(type, "pdf");
       File pdfFile = new File(pdf);
       if (pdfFile.exists()) {
           outFile(buffer, pdfFile, response);
       } else {
           FileInputStream in = new FileInputStream(path);
           ZipSecureFile.setMinInflateRatio(-1.0d);
           XMLSlideShow xmlSlideShow = new XMLSlideShow(in);
           in.close();
           // 获取大小
           Dimension pgsize = xmlSlideShow.getPageSize();
           // 获取幻灯片
           List<XSLFSlide> slides = xmlSlideShow.getSlides();
           List<File> imageList = new ArrayList<>();
           for (int i = 0; i < slides.size(); i++) {
               // 解决乱码问题
               List<XSLFShape> shapes = slides.get(i).getShapes();
               for (XSLFShape shape : shapes) {
                   if (shape instanceof XSLFTextShape) {
                       XSLFTextShape sh = (XSLFTextShape) shape;
                       List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                       for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
                           List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                           for (XSLFTextRun xslfTextRun : textRuns) {
                               xslfTextRun.setFontFamily("宋体");
                           }
                       }
                   }
               }
               //根据幻灯片大小生成图片
               BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
               Graphics2D graphics = img.createGraphics();
               graphics.setPaint(Color.white);
               graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
               // 将PPT内容绘制到img上
               slides.get(i).draw(graphics);
               //图片将要存放的路径
               String absolutePath = basePath + File.separator+ (i + 1) + ".jpg";
               File jpegFile = new File(absolutePath);
               if (!jpegFile.exists()) {
                   // 判断如果图片存在则不再重复创建,建议将图片存放到一个特定目录,后面会统一删除
                   FileOutputStream fileOutputStream = new FileOutputStream(jpegFile);
                   ImageIO.write(img, "jpg", fileOutputStream);
               }
               // 图片路径存放
               imageList.add(jpegFile);
           }
           File file = png2Pdf(imageList, pdf);
           outFile(buffer, file, response);
       }
   }
 
   private void outFile(byte[] buffer, File pdfFile, HttpServletResponse response) throws IOException {
       ByteArrayOutputStream out;
       int n = 0;
       FileInputStream fileInputStream = new FileInputStream(pdfFile);
       out = new ByteArrayOutputStream();
       ServletOutputStream outputStream = response.getOutputStream();
       while ((n = fileInputStream.read(buffer)) != -1) {
           out.write(buffer, 0, n);
       }
       outputStream.write(out.toByteArray());
       outputStream.flush();
   }
   //将图片列表转换为PDF格式文件并存储
   public File png2Pdf(List<File> pngFiles, String pdfFilePath) {
       Document document = new Document();
       File pdfFile = null;
       long startTime = System.currentTimeMillis();
       try {
           pdfFile = new File(pdfFilePath);
           if (pdfFile.exists()) {
               return pdfFile;
           }
           PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
           document.open();
           pngFiles.forEach(pngFile -> {
               try {
                   Image png = Image.getInstance(pngFile.getCanonicalPath());
                   png.scalePercent(50);
                   document.add(png);
               } catch (Exception e) {
                   System.out.println("png2Pdf exception");
               }
           });
           document.close();
           return pdfFile;
       } catch (Exception e) {
           System.out.println(String.format("png2Pdf %s exception", pdfFilePath));
       } finally {
           if (document.isOpen()) {
               document.close();
           }
           // 删除临时生成的png图片
           for (File pngFile : pngFiles) {
               try {
                   FileUtils.delete(pngFile);
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           long endTime = System.currentTimeMillis();
           System.out.println("png2Pdf耗时:" + (endTime - startTime));
       }
 
       return null;
   }

核心思路:将PPT文件读取每一页幻灯片,将幻灯片转换为图片格式,最后将所有图片放到一个pdf文件中形成一个pdf文件用于在线预览。预览时会在同级目录下创建一个相同文件名后缀为pdf的文件,每次预览会先查找文件是否存在,存在则直接预览,不存在则会走上面的处理。

4、预览效果

SpringBoot实现PPT格式文件上传并在线预览功能

到此这篇关于SpringBoot实现PPT格式文件上传并在线预览的文章就介绍到这了,更多相关SpringBoot PPT格式文件上传内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/pengyangyan/article/details/123086763

延伸 · 阅读

精彩推荐