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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
无小道4 分钟前
c++--typedef和#define的用法及区别
c语言·开发语言·汇编·c++
青云交24 分钟前
Java 大视界 -- Java 大数据在智能医疗远程手术机器人操作数据记录与分析中的应用(342)
java·大数据·数据记录·远程手术机器人·基层医疗·跨院协作·弱网络适配
输出的都是我的26 分钟前
latex格式中插入eps格式的图像的编译命令
pdf
知北游天31 分钟前
Linux:多线程---同步&&生产者消费者模型
java·linux·网络
SoniaChen3333 分钟前
Rust基础-part2-变量和可变类型
开发语言·后端·rust
钢铁男儿40 分钟前
C#接口实现详解:从理论到实践,掌握面向对象编程的核心技巧
java·前端·c#
深栈解码43 分钟前
第二章:Class文件解剖:字节码的二进制密码
java·后端
TeamDev1 小时前
从 JavaFX WebView 迁移至 JxBrowser
java·后端·webview
麦兜*1 小时前
【SpringBoot 】Spring Boot OAuth2 六大安全隐患深度分析报告,包含渗透测试复现、漏洞原理、风险等级及完整修复方案
java·jvm·spring boot·后端·spring·系统架构
用户40315986396631 小时前
在工作中学算法——专线配置
java·算法