Spring Boot 初學(xué)者指南:PDF 轉(zhuǎn)換為圖片或 Word 實(shí)現(xiàn)
作者:Java技術(shù)營地
Apache PDFBox是開源 Java 工具包,解析 PDF 準(zhǔn)確,支持內(nèi)容提取、文檔創(chuàng)建等,適合初學(xué)者。
一、工具選型與準(zhǔn)備
Apache PDFBox :開源 Java 工具包,解析 PDF 準(zhǔn)確,支持內(nèi)容提取、文檔創(chuàng)建等,適合初學(xué)者。
項(xiàng)目依賴 :在 pom.xml 中添加以下關(guān)鍵依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
二、Spring Boot 實(shí)現(xiàn) PDF 轉(zhuǎn)圖片
1. 文件上傳功能
前端表單 :用于上傳 PDF 文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF 轉(zhuǎn)換為圖片</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept=".pdf"/>
<button type="submit">上傳 PDF</button>
</form>
</body>
</html>
后端接口 :處理文件上傳。
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 設(shè)置文件保存路徑
Path uploadPath = Paths.get("uploads");
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 保存文件到本地
Path filePath = Paths.get(uploadPath + "/" + file.getOriginalFilename());
Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok("文件上傳成功!");
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上傳失敗!");
}
}
2. PDF 轉(zhuǎn)圖片核心邏輯
@Service
public class PdfToImageService {
public void convertPdfToImage(String pdfPath, String outputFolder) throws IOException {
// 加載 PDF 文件
try (PDDocument document = PDDocument.load(new File(pdfPath))) {
PDFRenderer renderer = new PDFRenderer(document);
// 遍歷每一頁進(jìn)行渲染
for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
BufferedImage image = renderer.renderImageWithDPI(pageIndex, 300, ImageType.RGB);
// 保存為圖片
String imageName = "page_" + (pageIndex + 1) + ".png";
ImageIO.write(image, "PNG", new File(outputFolder + "/" + imageName));
}
}
}
}
3. 圖片下載功能
@GetMapping("/download/image/{fileName}")
public ResponseEntity<InputStreamResource> downloadImage(@PathVariable String fileName) throws IOException {
// 設(shè)置資源文件路徑
String filePath = "uploads/" + fileName;
InputStreamResource resource = new InputStreamResource(new FileInputStream(filePath));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
return ResponseEntity.ok()
.headers(headers)
.contentLength(new File(filePath).length())
.contentType(MediaType.IMAGE_PNG)
.body(resource);
}
三、Spring Boot 實(shí)現(xiàn) PDF 轉(zhuǎn) Word
(技術(shù)文章篇幅限制,此處僅展示關(guān)鍵代碼片段)
// 引入 OpenAPI 庫
// 在 porm.xml 中添加依賴
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.28.3</version>
</dependency>
<dependency>
<groupId> org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
private void convertPdfToWord(String pdfPath, String docPath) throws Exception {
// 解析 PDF 文本
InputStream input = new FileInputStream(pdfPath);
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
PDFParser pdfParser = new PDFParser();
pdfParser.parse(input, handler, metadata, context);
String text = handler.toString();
// 將文本寫入 Word 文檔
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(text);
// 保存 Word 文檔
FileOutputStream out = new FileOutputStream(docPath);
document.write(out);
out.close();
}
四、測試與運(yùn)行
- 啟動(dòng)項(xiàng)目 :運(yùn)行 DocumentConverterApplication 類中的 main 方法。
- 上傳測試 :訪問 /upload 接口上傳 PDF 文件。
- 轉(zhuǎn)換測試 :調(diào)用 PDF 轉(zhuǎn)換服務(wù),將在指定輸出路徑生成圖片或 Word 文件。
- 下載測試 :訪問 /download/image/{fileName} 接口,下載轉(zhuǎn)換后的圖片或 Word 文件。
責(zé)任編輯:趙寧寧
來源:
Java技術(shù)營地