首页 > 其他分享 >Spring Boot集成OpenPDF实现PDF导出功能

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

时间:2024-09-23 10:25:09浏览次数:1  
标签:java OpenPDF Spring Boot HTML PDF new 模板

如果你想要在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的依赖:

Xml

深色版本

1<dependency>
2 <groupId>com.github.openpdf</groupId>
3 <artifactId>openpdf</artifactId>
4 <version>1.3.14</version>
5</dependency>

2.2 创建实体类

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

Java

深色版本

1import java.time.LocalDate;
2
3public class Invoice {
4
5 private String invoiceNumber;
6 private LocalDate issueDate;
7 private String customerName;
8 private double totalAmount;
9
10 // 构造器、getter和setter...
11
12 public Invoice(String invoiceNumber, LocalDate issueDate, String customerName, double totalAmount) {
13 this.invoiceNumber = invoiceNumber;
14 this.issueDate = issueDate;
15 this.customerName = customerName;
16 this.totalAmount = totalAmount;
17 }
18
19 // Getter and setter methods...
20}

3. 创建HTML模板

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

Html

深色版本

1<!DOCTYPE html>
2<html>
3<head>
4 <style>
5 body { font-family: Arial; }
6 table { width: 100%; border-collapse: collapse; }
7 td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; }
8 </style>
9</head>
10<body>
11 <h2>Invoice</h2>
12 <table>
13 <tr>
14 <th>Invoice Number:</th>
15 <td>${invoiceNumber}</td>
16 </tr>
17 <tr>
18 <th>Issue Date:</th>
19 <td>${issueDate}</td>
20 </tr>
21 <tr>
22 <th>Customer Name:</th>
23 <td>${customerName}</td>
24 </tr>
25 <tr>
26 <th>Total Amount:</th>
27 <td>${totalAmount}</td>
28 </tr>
29 </table>
30</body>
31</html>

4. 使用OpenPDF生成PDF

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

Java

深色版本

1import com.lowagie.text.Document;
2import com.lowagie.text.pdf.PdfWriter;
3import com.lowagie.text.pdf.parser.PdfTextExtractor;
4import freemarker.template.Configuration;
5import freemarker.template.Template;
6import freemarker.template.TemplateException;
7import org.springframework.stereotype.Controller;
8import org.springframework.web.bind.annotation.GetMapping;
9import org.springframework.web.bind.annotation.ResponseBody;
10
11import javax.servlet.http.HttpServletResponse;
12import java.io.ByteArrayOutputStream;
13import java.io.IOException;
14import java.io.OutputStream;
15import java.io.StringWriter;
16import java.nio.charset.StandardCharsets;
17import java.util.HashMap;
18import java.util.Map;
19
20@Controller
21public class PdfController {
22
23 @GetMapping("/generate-pdf")
24 @ResponseBody
25 public void generatePdf(HttpServletResponse response) throws IOException, TemplateException {
26 // 设置HTTP响应头
27 response.setContentType("application/pdf");
28 response.setHeader("Content-Disposition", "attachment; filename=invoice.pdf");
29
30 // 创建Invoice实例
31 Invoice invoice = new Invoice("INV-123456", LocalDate.now(), "John Doe", 250.99);
32
33 // 使用FreeMarker处理HTML模板
34 Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
35 cfg.setClassForTemplateLoading(PdfController.class, "/templates/"); // 假设HTML模板位于/templates/目录下
36
37 Map<String, Object> data = new HashMap<>();
38 data.put("invoice", invoice);
39
40 Template template = cfg.getTemplate("invoice.html");
41 StringWriter stringWriter = new StringWriter();
42 template.process(data, stringWriter);
43
44 // 将HTML字符串转换为PDF
45 ByteArrayOutputStream pdfBytes = new ByteArrayOutputStream();
46 try (Document document = new Document()) {
47 PdfWriter.getInstance(document, pdfBytes);
48 document.open();
49 com.lowagie.text.html.HtmlWriter.getInstance(document, pdfBytes);
50 com.lowagie.text.html.simpleparser.HTMLWorker htmlParser = new com.lowagie.text.html.simpleparser.HTMLWorker(document);
51 htmlParser.parse(new StringReader(stringWriter.toString()));
52 document.close();
53 }
54
55 // 输出PDF到浏览器
56 OutputStream out = response.getOutputStream();
57 out.write(pdfBytes.toByteArray());
58 out.flush();
59 out.close();
60 }
61}

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

注意事项

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

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

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

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

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

标签:java,OpenPDF,Spring,Boot,HTML,PDF,new,模板
From: https://www.cnblogs.com/qxqbk/p/18426524

相关文章