Spring Boot如何使用 ITextPDF生成 PDF 文件

x33g5p2x  于2022-09-14 转载在 Spring  
字(7.8k)|赞(0)|评价(0)|浏览(671)

在这篇文章中,我们将讨论如何使用 Spring Boot、thymeleaf 和 Itext 库生成 PDF 文件。

理解 Itext PDF

该库通过手动创建每个元素或将 HTML+CSS 转换为 PDF 来帮助生成 PDF 文件。这个库提供的方法很简单。让我们看看这两种方法的实际效果。

从 HTML 生成 PDF

首先,我们需要以下 Maven 依赖项。

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.1.12</version>
        </dependency>
Code language: HTML, XML (xml)

Itext 库附带一个名为 html2pdf 的支持库,可以将 Html 和 CSS 转换为视觉上令人愉悦的 PDF 文档。与使用 Java 代码不同,此方法易于实现。因此,让我们将该依赖项也添加到我们的 java 项目中。

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>3.0.1</version>
        </dependency>
Code language: HTML, XML (xml)
<!doctype html>
<html lang="en">
<head>
    <title>SpringHow html to pdf</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
     <div>
        <p >Lorum ipsum some text before image. Lorum ipsum some text before image. Lorum ipsum some text before image. Lorum ipsum some text before image. Lorum ipsum some text before image. Lorum ipsum some text before image. Lorum ipsum some text before image. Lorum ipsum some text before image. </p>
        <img src="photo.jpg" alt="Orange">
        <p >Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image. Lorum ipsum some text after image.</p>
        <table>
            <tr><th>Product</th><th>Quantity</th><th>Price</th><th>Total</th></tr>
            <tr><td>Jeans</td><td>2</td><td>10.99</td><td>20.98</td></tr>
            <tr><td>Shirt</td><td>2</td><td>7.99</td><td>14.98</td></tr>
        </table>
     </div>
</body>
</html>
Code language: HTML, XML (xml)

将上述 HTML 称为 pdf-input.html。我在 styles.css 文件中放置了适当的样式。你可以使用你自己的。有了这些,让我们在 Java 代码中调用 HtmlConverter.convertToPdf 方法。

import java.io.*;
import com.itextpdf.html2pdf.HtmlConverter;

public class GeneratePDFUsingHTML {

    public static void main(String[] args) throws IOException {

        HtmlConverter.convertToPdf(new File("./pdf-input.html"),new File("demo-html.pdf"));
    }
}
Code language: JavaScript (javascript)

这个辅助方法接受一个输入 HTML 文件,解析它应用 CSS 并将其转换为 pdf 输出。这种方法很简单,不是吗?更新 HTML 文件比深入研究一千行代码要好得多。这是结果。


HTML 到 PDF 使用 Java 和 ITEXT PDF

我们可以在 java 应用程序中的任何地方使用上述方法来生成丰富且视觉上令人愉悦的 PDF 文件。尽管这似乎是创建 PDF 文件的好方法,但我们仍然缺乏创建动态 PDF 文件的能力。

从 MVC 视图生成 PDF

带有模板引擎的 Spring MVC 可以提供动态的 HTML 内容。我们可以使用以下方法轻松地将这些转换为 PDF 响应。对于此示例,我将 spring-boot-starter-webspring-boot-starter-thymeleaf 导入到我的 Spring Boot 项目中以支持 MVC 和 thymeleaf。您可以使用自己选择的模板引擎。看看下面的这个百里香模板。这将为我们生成订单详细信息。此外,我还有一个来自 OrderHelper 的辅助方法来生成一些虚拟订单内容。

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
          name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <title>Spring Boot - Thymeleaf</title>
    <link th:href="@{/main.css}" rel="stylesheet"/>
</head>
<body class="flex items-center justify-center h-screen">
<div class="rounded-lg border shadow-lg p-10 w-3/5">
    <div class="flex flex-row justify-between pb-4">
        <div>
            <h2 class="text-xl font-bold">Order #<span class="text-green-600" th:text="${orderEntry.orderId}"></span>
            </h2>
        </div>
        <div>
            <div class="text-xl font-bold" th:text="${orderEntry.date}"></div>
        </div>
    </div>
    <div class="flex flex-col pb-8">
        <div class="pb-2">
            <h2 class="text-xl font-bold">Delivery Address</h2>
        </div>
        <div th:text="${orderEntry.account.address.street}"></div>
        <div th:text="${orderEntry.account.address.city}"></div>
        <div th:text="${orderEntry.account.address.state}"></div>
        <div th:text="${orderEntry.account.address.zipCode}"></div>

    </div>
    <table class="table-fixed w-full text-right border rounded">
        <thead class="bg-gray-100">
        <tr>
            <th class="text-left pl-4">Product</th>
            <th>Qty</th>
            <th>Price</th>
            <th class="pr-4">Total</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="item : ${orderEntry.items}">
            <td class="pl-4 text-left" th:text="${item.name}"></td>
            <td th:text="${item.quantity}"></td>
            <td th:text="${item.price}"></td>
            <td class="pr-4" th:text="${item.price * item.quantity}"></td>
        </tr>
        </tbody>
    </table>
    <div class="flex flex-row-reverse p-5">
        <h2 class="font-medium  bg-gray-200 p-2 rounded">
            Grand Total: <span class="text-green-600" th:text="${orderEntry.payment.amount}"></span>
        </h2>
    </div>
    <h2 class="text-xl font-bold">Payment Details</h2>
    <table class="table-fixed text-left w-2/6 border">
        <tr>
            <th class="text-green-600">Card Number</th>
            <td th:text="${orderEntry.payment.cardNumber}"></td>
        </tr>
        <tr>
            <th class="text-green-600">CVV</th>
            <td th:text="${orderEntry.payment.cvv}"></td>
        </tr>
        <tr>
            <th class="text-green-600">Expires (MM/YYYY)</th>
            <td th:text="${orderEntry.payment.month +'/'+ orderEntry.payment.year}"></td>
        </tr>
    </table>
</div>
</body>
</html>
Code language: HTML, XML (xml)
@RequestMapping(path = "/")
    public String getOrderPage(Model model) throws IOException {
        Order order = OrderHelper.getOrder()
        model.addAttribute("orderEntry", order);
        return "order";
    }
Code language: JavaScript (javascript)

通过上述设置,您在点击控制器 API 时的响应如下所示。


要转换为 PDF 的示例 HTML 视图

要将此 MVC 响应转换为 PDF,您只需接管 thymeleaf 生成的 HTML 内容并使用 HtmlConverter 将其转换为 PDF。

@RequestMapping(path = "/pdf")
public ResponseEntity<?> getPDF(HttpServletRequest request, HttpServletResponse response) throws IOException {

    /* Do Business Logic*/

    Order order = OrderHelper.getOrder();

    /* Create HTML using Thymeleaf template Engine */

    WebContext context = new WebContext(request, response, servletContext);
    context.setVariable("orderEntry", order);
    String orderHtml = templateEngine.process("order", context);

    /* Setup Source and target I/O streams */

    ByteArrayOutputStream target = new ByteArrayOutputStream();

    /*Setup converter properties. */
    ConverterProperties converterProperties = new ConverterProperties();
    converterProperties.setBaseUri("http://localhost:8080");

    /* Call convert method */
    HtmlConverter.convertToPdf(orderHtml, target, converterProperties);  

    /* extract output as bytes */
    byte[] bytes = target.toByteArray();


    /* Send the response as downloadable PDF */

    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_PDF)
            .body(bytes);

}
Code language: PHP (php)

测试 Spring Boot PDF 生成

我已经在 /orders/pdf/ 上编写了我的控制器方法,这是我从浏览器点击 URL 时的结果。


Spring Boot PDF 生成使用 ITEXT PDF 和 Thymeleaf

在这里您可以看到响应是一个 PDF 文档。您可以通过 Chrome 的 PDF 查看器的外观来确认这一点。

Spring Boot 中使用 HTML 转 PDF 时的注意事项

  • converterProperties.setBaseUri 很重要。否则,/main.css 等静态资源将从本地路径解析。
  • 您可以注意到,与 HTML 对应元素相比,某些元素移动了一点或未对齐。此行为是由于库不支持某些 CSS 属性。但是您始终可以调整 CSS 以获得最佳效果。
  • 密切关注不受支持的 CSS 属性的日志。例如,Unsupported pseudo CSS selector: :-moz-focusring。只要继续生成 PDF,您就可以放心地忽略该错误。
  • 如果您需要按要求下载文件,则可以添加如下所示的配置。
return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=order.pdf") 
                .contentType(MediaType.APPLICATION_PDF) 
                .body(bytes);
Code language: JavaScript (javascript)

这就是我目前关于这个话题的全部内容。该示例在 Github repository 中查看。

相关文章

微信公众号

最新文章

更多