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 分钟前
Spark学习基础转换算子案例(单词计数(WordCount))
java·大数据·分布式·学习·spark·maven
夏日听雨眠11 分钟前
Linux(信号,管道,共享内存)
java·服务器·网络
TANGLONG22211 分钟前
【C++】继承详解——基类/派生类、作用域、默认函数、菱形继承(超详细)
java·c语言·c++·经验分享·笔记·ajax
zmsofts19 分钟前
IntelliJ IDEA)因为内存不足而崩溃
java·ide·intellij-idea
2501_9307077825 分钟前
使用C#代码压平 PDF 表单字段
数据库·pdf·c#
Dlrb121126 分钟前
C语言-字符串指针与函数指针
java·c语言·前端
铅笔小新z27 分钟前
【C语言】数据类型和变量
c语言·开发语言
萝卜白菜。30 分钟前
通过cmdline-jmxclient.jar采集TongWeb8.0监控值
java·jar
code_whiter33 分钟前
C++11(stack和queue)
开发语言·c++
最后一支迷迭香36 分钟前
苹果的MacOS系统适合做Java开发吗
java·开发语言·macos