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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
佳xuan4 分钟前
模型训练之爬取数据
开发语言·python
bupt_015 分钟前
Hermes深入理解及源码解析(二):Hermes的记忆机制
java·服务器·前端
之歆10 分钟前
DAY_10 JavaScript 深度解析:原型链 · 引用类型 · 内置对象 · 数组方法全攻略(上)
开发语言·javascript·ecmascript
zmzb010312 分钟前
Python课后习题训练记录Day122
开发语言·python
Ting-yu19 分钟前
Spring AI Alibaba零基础速成(1) ---- 项目创建与配置
java·人工智能·spring
喜欢coding的谢同学21 分钟前
ArthasClaw:用自然语言诊断 JVM 的 AI 助手,告别繁琐的 Arthas 命令
java·人工智能·arthas
陳土21 分钟前
R语言jiebaR包使用摘要
开发语言·r语言
Evand J22 分钟前
【MATLAB】多无人机编队协同控制与三维航迹规划仿真。障碍物斥力避障,输出编队误差、控制输入、三维轨迹等
开发语言·matlab·无人机
froginwe1139 分钟前
jQuery UI 小部件方法调用
开发语言
信奥胡老师40 分钟前
B3930 [GESP202312 五级] 烹饪问题
开发语言·数据结构·c++·学习·算法