springboot Apache PDFBox 通过路径参数读取文件信息流,并转化为pdf 在网页预览
实现要点说明:
通过@PathVariable接收文件路径参数,动态读取指定文件
使用PDFBox创建PDF文档对象并添加内容流
设置响应头为application/pdf和inline模式实现浏览器直接预览
通过ByteArrayOutputStream将PDF转换为字节数组返回
添加中文字体支持依赖确保中文内容正常显示
使用方式:
启动应用后访问:http://localhost:8080/api/pdf/preview/文件路径
浏览器将自动加载PDF预览界面
支持任意文本文件转换为PDF预览
pom.xml 添加配置
<dependencies><!-- Spring Boot Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- PDFBox核心库 --><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.29</version></dependency><!-- 中文字体支持 --><dependency><groupId>com.github.librepdf</groupId><artifactId>openpdf</artifactId><version>1.3.30</version></dependency>
</dependencies>
编写controller
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.nio.file.Files;@RestController
@RequestMapping("/api/pdf")
public class PdfController {@GetMapping("/preview/{filePath:.+}")public ResponseEntity<byte[]> previewPdf(@PathVariable String filePath) throws IOException {File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException("文件不存在");}try (PDDocument document = new PDDocument()) {PDPage page = new PDPage();document.addPage(page);// 读取文件内容并写入PDFtry (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);contentStream.beginText();contentStream.newLineAtOffset(100, 700);contentStream.showText("文件内容预览: " + file.getName());contentStream.newLineAtOffset(0, -20);// 读取文件内容String content = new String(Files.readAllBytes(file.toPath()));contentStream.showText(content.substring(0, Math.min(content.length(), 1000)));contentStream.endText();}ByteArrayOutputStream outputStream = new ByteArrayOutputStream();document.save(outputStream);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_PDF);headers.setContentDispositionFormData("inline", "preview.pdf");return ResponseEntity.ok().headers(headers).body(outputStream.toByteArray());}}
}
配置文件里面添加:
application.properties
# 允许访问静态资源
spring.mvc.static-path-pattern=/**
spring.web.resources.static-locations=classpath:/static/# 文件上传大小限制
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB