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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
BUG研究员_4 小时前
Runnable与LCEL
开发语言·人工智能·python
码农颜5 小时前
5.4.1 锁分类
java·数据库·mysql
牛艺翔6 小时前
C++基础
开发语言·c++
键盘会跳舞6 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
linux-hzh6 小时前
百日算法修炼 · Day 03
java·算法
美味蛋炒饭.6 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息6 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
不负岁月无痕6 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
mister_guo7 小时前
Java线程池参数应该如何设置(ThreadPoolExecutor)
java
余额瞒着我当琳7 小时前
C++模板初阶与STL初探
android·java·c++