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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
暮冬-  Gentle°1 小时前
C++中的命令模式实战
开发语言·c++·算法
Volunteer Technology4 小时前
架构面试题(一)
开发语言·架构·php
清水白石0084 小时前
Python 对象序列化深度解析:pickle、JSON 与自定义协议的取舍之道
开发语言·python·json
2401_876907524 小时前
Python机器学习实践指南
开发语言·python·机器学习
努力中的编程者5 小时前
栈和队列(C语言底层实现环形队列)
c语言·开发语言
回到原点的码农5 小时前
Spring Data JDBC 详解
java·数据库·spring
gf13211115 小时前
python_查询并删除飞书多维表格中的记录
java·python·飞书
zb200641205 小时前
Spring Boot 实战:轻松实现文件上传与下载功能
java·数据库·spring boot
一勺菠萝丶5 小时前
Flowable + Spring 集成踩坑:流程结束监听器查询历史任务为空 & 获取不到审批意见
java·数据库·spring
jwn9995 小时前
Spring Boot 整合 Keycloak
java·spring boot·后端