在Spring Boot项目中实现Word转PDF并预览

在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文件,转换过程可能比较耗时,可以考虑使用异步处理或任务队列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖牛马人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值