java springboot2.7 写一个本地 pdf 预览的接口

依赖方面 创建的是 接口web项目就好了

然后包管理工具打开需要这些

java 复制代码
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

然后 例如这里我要预览 本地 E盘下的 ydzxmgf下的git分支管理规范.pdf文件 就可以这样写

java 复制代码
@GetMapping("/pdf")
    public ResponseEntity<Resource> previewPdfFile() throws IOException {
        // 指定文件路径
        String filePath = "E:/ydzxmgf/git分支管理规范.pdf";

        // 创建文件资源
        File file = new File(filePath);
        Path path = Paths.get(file.getAbsolutePath());
        Resource resource = new FileSystemResource(file);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + file.getName());
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_PDF)
                .body(resource);
    }

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
2601_953824612 分钟前
基于SSM的水果超市管理系统
java·tomcat·maven
guo_wen_qiang4 分钟前
springboot如何自定义一个启动器starter
java·spring boot·intellij-idea
Lazionr7 分钟前
二叉搜索树:从树形结构到高效查找
开发语言·c++
此生决int8 分钟前
深入理解C++系列(21)——异常
开发语言·c++
许彰午8 分钟前
55-字典缓存与通知SPI
java·低代码·架构
captain37613 分钟前
HTTP(2)
java·网络·http·java-ee
徐子童15 分钟前
介绍MVCC机制
java·mysql·面试题·秋招·并发·mvcc
Wang's Blog16 分钟前
Java 项目实战: 外卖平台-启用禁用员工账号与Long精度丢失修复
java·服务器
乌暮21 分钟前
Java 抽象类与接口详解:半成品图纸 vs 能力合同
java·开发语言·后端·学习
乐观的Terry28 分钟前
ShipDesk 完整使用教程:从新建项目到 SSH 自动发布
开发语言