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 分钟前
Java中的继承:从入门到精通
java·继承
froginwe112 分钟前
jQuery 隐藏/显示详解
开发语言
bearpping5 分钟前
怎么下载安装yarn
java
码云数智-大飞10 分钟前
分布式数据库:2026年数据架构的基石与挑战
开发语言
西门吹雪分身17 分钟前
JDK8之四大核心函数式接口
java·函数式接口
查古穆24 分钟前
python进阶-推导式
开发语言·python
华科易迅28 分钟前
Spring AOP
java·后端·spring
架构师沉默31 分钟前
Gemini 正式登陆香港,不用翻墙!
java·后端·架构
njidf32 分钟前
C++中的访问者模式
开发语言·c++·算法
英俊潇洒美少年1 小时前
js 同步异步,宏任务微任务的关系
开发语言·javascript·ecmascript