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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
一个处女座的程序猿O(∩_∩)O16 分钟前
Python面向对象的多态特性详解
开发语言·python
yngsqq31 分钟前
多段线顶点遍历技巧(适用闭合和非闭合)
开发语言
宇木灵34 分钟前
C语言基础-五、数组
c语言·开发语言·学习·算法
想用offer打牌35 分钟前
一站式了解接口防刷(限流)的基本操作
java·后端·架构
xyq20241 小时前
空对象模式
开发语言
姜源Jerry1 小时前
【Trae】Trae IDE&SOLO浅尝
java·ide·ai
宇木灵1 小时前
C语言基础-三、流程控制语句
java·c语言·前端
不懒不懒2 小时前
【Python办公自动化进阶指南:系统交互与网页操作实战】
开发语言·python·交互
普通网友2 小时前
C++与Rust交互编程
开发语言·c++·算法
游乐码2 小时前
c#静态类和静态构造函数
开发语言·c#