在Spring Boot项目中实现Word转PDF并进行前端网页预览,你可以使用Apache POI来读取Word文件,iText或Apache PDFBox来生成PDF文件,然后通过Spring Boot控制器提供文件下载或预览链接。以下是一个示例实现步骤和代码:
1. 添加依赖
在pom.xml
中添加必要的依赖:
<dependencies>
<!-- Spring Boot Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache POI 用于处理 Word 文件 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<!-- iText 用于生成 PDF 文件 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.15</version>
</dependency>
<!-- 或者使用 Apache PDFBox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
</dependencies>
2. 创建服务类
创建一个服务类来处理Word到PDF的转换:
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
@Service
public class WordToPdfService {
public File convertWordToPdf(File wordFile, String outputPdfPath) throws IOException {
XWPFDocument document = new XWPFDocument(new FileInputStream(wordFile));
File pdfFile = new File(outputPdfPath);
FileOutputStream out = new FileOutputStream(pdfFile);
// 使用 iText 或 PDFBox 进行转换
// 这里只是一个示例,实际转换逻辑需要根据所选库进行实现
// 例如使用 iText 7 的代码:
com.itextpdf.kernel.pdf.PdfWriter pdfWriter = new com.itextpdf.kernel.pdf.PdfWriter(out);
com.itextpdf.layout.Document pdfDocument = new com.itextpdf.layout.Document(pdfWriter);
for (XWPFParagraph paragraph : document.getParagraphs()) {
pdfDocument.add(new com.itextpdf.layout.element.Paragraph(paragraph.getText()));
}
pdfDocument.close();
return pdfFile;
}
}
3. 创建控制器
创建一个控制器来处理文件上传和转换请求:
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@RequestMapping("/api")
public class WordToPdfController {
private final WordToPdfService wordToPdfService;
private final Path uploadDir = Paths.get("uploads");
public WordToPdfController(WordToPdfService wordToPdfService) {
this.wordToPdfService = wordToPdfService;
// 创建上传目录
uploadDir.toFile().mkdirs();
}
@PostMapping("/convert")
public ResponseEntity<?> convertWordToPdf(@RequestParam("file") MultipartFile file) throws IOException {
// 保存上传的 Word 文件
Path wordFilePath = uploadDir.resolve(file.getOriginalFilename());
Files.copy(file.getInputStream(), wordFilePath);
// 转换为 PDF
String pdfFileName = file.getOriginalFilename().replace(".docx", ".pdf");
File pdfFile = wordToPdfService.convertWordToPdf(wordFilePath.toFile(), uploadDir.resolve(pdfFileName).toString());
// 返回 PDF 预览链接
String pdfUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/api/download/")
.path(pdfFileName)
.toUriString();
return ResponseEntity.ok().body("PDF 文件已生成,可以通过以下链接预览: <a href=\"" + pdfUrl + "\">预览 PDF</a>");
}
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException {
Path pdfPath = uploadDir.resolve(fileName);
Resource resource = new UrlResource(pdfPath.toUri());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
4. 前端实现
在前端,你可以使用HTML表单上传Word文件并显示PDF预览链接:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word to PDF Converter</title>
</head>
<body>
<h1>Word to PDF Converter</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" accept=".docx" required>
<button type="submit">Convert to PDF</button>
</form>
<div id="result"></div>
<script>
document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
fetch('/api/convert', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
</body>
</html>
5. 注意事项
以上代码提供了一个基本的实现框架,你可以根据具体需求进行调整和扩展。
-
文件存储:目前示例代码将上传的Word文件和生成的PDF文件存储在项目根目录下的
uploads
文件夹中。在实际生产环境中,你可能需要配置持久化存储或云存储服务。 -
文件大小限制:Spring Boot默认有文件上传大小限制,你可以在
application.properties
中配置:spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB
-
安全性:在实际应用中,应增加文件类型验证、防止目录遍历攻击等安全措施。
-
性能优化:对于较大的Word文件,转换过程可能比较耗时,可以考虑使用异步处理或任务队列。