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_962885729 分钟前
如何用 Python 计算溃疡指数(Ulcer Index)?
开发语言·python
kiracrimson20 分钟前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
code2cat25 分钟前
【随笔】RAG检索缓存:复用证据之前,先把权限和版本放进缓存键
java·人工智能·缓存·知识库·rag
程序边界32 分钟前
顶刊级论文配图全流程:用 Python 复刻 Nature/Science 风格图表
开发语言·python
普通人633 分钟前
uniapp模版JS
开发语言·javascript·小程序·uni-app·1024程序员节
\光辉岁月/40 分钟前
2.spring5-IOC
java·容器·ioc·注解
G018_star sky♬1 小时前
nodeJS他是如何用JavaScript封装C++的呢
开发语言·javascript·c++
java_nnnn1 小时前
Spring MVC小案例(1)
java·后端·spring·mvc
wyhwust1 小时前
程序设计基础--C语言输入输出单元测试
c语言·开发语言
西凉的悲伤1 小时前
Spring Boot 条件装配注解详解
java·springboot·1024程序员节·条件装配