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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
aq55356001 分钟前
Laravel 10.x重磅升级:PHP 8.1+新时代
开发语言·php·laravel
shaoFan12 分钟前
关于java 调用阿里千问大模型,流式返回,并返回给前端
java·前端·状态模式
雪碧聊技术2 分钟前
Java历史—沙箱安全机制
java·安全·沙箱机制
java1234_小锋3 分钟前
Spring AI 2.0 开发Java Agent智能体 - Spring AI 2.0简介
java·人工智能·spring·spring ai
秋雨梧桐叶落莳7 分钟前
iOS——Masonry约束内容整理
开发语言·学习·macos·ios·objective-c·cocoa
Hesionberger8 分钟前
LeetCode72.编辑距离(多维动态规划)
java·开发语言·c++·python·算法
人道领域15 分钟前
【LeetCode刷题日记】1047:双栈法与双指针法巧妙消除相邻重复字符
java·算法·leetcode·职场和发展
Via_Neo15 分钟前
Bash Game
开发语言·bash
小脑斧12315 分钟前
Adobe PDF 编辑器 破截一键激火
adobe·pdf
菜菜的顾清寒36 分钟前
C++面试题自用-持续更新
开发语言·c++