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);
    }

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
南桥几晴秋2 分钟前
QT按钮控件
开发语言·qt
xj7573065339 分钟前
《python web开发 测试驱动方法》
开发语言·前端·python
IT 行者19 分钟前
Spring Boot 4.x 安全监控新篇章:基于 ObservationFilterChainDecorator 的可观测性实践
java·spring boot·后端
pyniu23 分钟前
Spring Boot租房管理系统
java·spring boot·后端
CSDN_RTKLIB26 分钟前
inline内联函数基础知识
开发语言·c++
No0d1es27 分钟前
2025年12月 GESP CCF编程能力等级认证Python四级真题
开发语言·python·青少年编程·等级考试·gesp·ccf
love530love28 分钟前
EPGF 新手教程 13在 PyCharm(中文版 GUI)中创建 Hatch 项目环境,并把 Hatch 做成“项目自包含”(工具本地化为必做环节)
开发语言·ide·人工智能·windows·python·pycharm·hatch
Ralph_Y34 分钟前
C++异常对象
开发语言·c++
野生技术架构师36 分钟前
TokenRetryHelper 详解与 Spring Boot 迁移方案
java·spring boot·后端
baiduopenmap37 分钟前
【智图译站】GENREGION——高准确度、高可扩展的城市区域自动划分方法
开发语言·百度地图