Spring Boot集成OpenPDF实现PDF导出功能

如果你想要在Spring Boot项目中使用OpenPDF来生成PDF文件,而不是iText,你可以通过将HTML转换成PDF的方式来实现。OpenPDF是一个开源的Java PDF库,它基于iText 5.x版本,但是它主要提供了HTML到PDF的转换能力。

下面是如何在Spring Boot项目中设置并使用OpenPDF来生成PDF文件的一个简单教程。

1. 引言

PDF文件因其跨平台兼容性和格式的稳定性而在商业文档中广泛使用。使用Spring Boot集成OpenPDF库可以方便地将HTML、JSON或其他数据源转换为PDF格式,以供下载或打印。

2. 准备工作

2.1 添加依赖

首先,在你的pom.xml文件中添加OpenPDF的依赖:

<dependency>
    <groupId>com.github.openpdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.3.14</version>
</dependency>

2.2 创建实体类

假设我们有一个简单的Invoice实体类,用于存储发票信息:

import java.time.LocalDate;

public class Invoice {

    private String invoiceNumber;
    private LocalDate issueDate;
    private String customerName;
    private double totalAmount;

    // 构造器、getter和setter...

    public Invoice(String invoiceNumber, LocalDate issueDate, String customerName, double totalAmount) {
        this.invoiceNumber = invoiceNumber;
        this.issueDate = issueDate;
        this.customerName = customerName;
        this.totalAmount = totalAmount;
    }

    // Getter and setter methods...
}

3. 创建HTML模板

为了将数据转换为PDF文件,我们需要创建一个HTML模板,该模板定义了PDF文件的样式和布局。

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial; }
        table { width: 100%; border-collapse: collapse; }
       td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; }
    </style>
</head>
<body>
    <h2>Invoice</h2>
    <table>
        <tr>
            <th>Invoice Number:</th>
            <td>${invoiceNumber}</td>
        </tr>
        <tr>
            <th>Issue Date:</th>
            <td>${issueDate}</td>
        </tr>
        <tr>
            <th>Customer Name:</th>
            <td>${customerName}</td>
        </tr>
        <tr>
            <th>Total Amount:</th>
            <td>${totalAmount}</td>
        </tr>
    </table>
</body>
</html>

4. 使用OpenPDF生成PDF

接下来,我们需要编写一个控制器方法,该方法读取HTML模板,填充数据,并将其转换为PDF文件。

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.parser.PdfTextExtractor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PdfController {

    @GetMapping("/generate-pdf")
    @ResponseBody
    public void generatePdf(HttpServletResponse response) throws IOException, TemplateException {
        // 设置HTTP响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=invoice.pdf");

        // 创建Invoice实例
        Invoice invoice = new Invoice("INV-123456", LocalDate.now(), "John Doe", 250.99);

        // 使用FreeMarker处理HTML模板
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setClassForTemplateLoading(PdfController.class, "/templates/"); // 假设HTML模板位于/templates/目录下

        Map<String, Object> data = new HashMap<>();
        data.put("invoice", invoice);

        Template template = cfg.getTemplate("invoice.html");
        StringWriter stringWriter = new StringWriter();
        template.process(data, stringWriter);

        // 将HTML字符串转换为PDF
        ByteArrayOutputStream pdfBytes = new ByteArrayOutputStream();
        try (Document document = new Document()) {
            PdfWriter.getInstance(document, pdfBytes);
            document.open();
            com.lowagie.text.html.HtmlWriter.getInstance(document, pdfBytes);
            com.lowagie.text.html.simpleparser.HTMLWorker htmlParser = new com.lowagie.text.html.simpleparser.HTMLWorker(document);
            htmlParser.parse(new StringReader(stringWriter.toString()));
            document.close();
        }

        // 输出PDF到浏览器
        OutputStream out = response.getOutputStream();
        out.write(pdfBytes.toByteArray());
        out.flush();
        out.close();
    }
}

在这个示例中,我们使用了Freemarker作为模板引擎来渲染HTML页面。如果你不使用Freemarker,你可以选择其他的模板引擎或者直接使用静态HTML文件。

注意事项

  • 在实际生产环境中,你可能需要考虑更复杂的HTML布局以及CSS样式。

  • 如果你需要支持中文等非英文字符,可能需要对字体进行额外配置。

  • 以上代码片段只是一个基本的示例,你可能需要根据实际情况进行调整。

这样,当用户访问/generate-pdf URL时,他们将能够下载生成的PDF文件。

以上步骤展示了如何在Spring Boot中集成OpenPDF并生成PDF文件的基本流程。希望这可以帮助你快速上手!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

missterzy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值