最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用SpringBoot集成Thymeleaf和Flying?Saucer實現(xiàn)PDF導(dǎo)出

 更新時間:2024年11月07日 08:36:58   作者:(???????)920  
在?Spring?Boot?項目中,生成?PDF?報表或發(fā)票是常見需求,本文將介紹如何使用?Spring?Boot?集成?Thymeleaf?模板引擎和?Flying?Saucer?實現(xiàn)?PDF?導(dǎo)出,并提供詳細的代碼實現(xiàn)和常見問題解決方案,需要的朋友可以參考下

一、項目依賴

要實現(xiàn) PDF 導(dǎo)出功能,首先需要在項目中添加以下依賴:

<dependencies>
    <!-- Thymeleaf模板引擎 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- Flying Saucer for PDF generation -->
    <dependency>
        <groupId>org.xhtmlrenderer</groupId>
        <artifactId>flying-saucer-pdf</artifactId>
        <version>9.1.22</version>
    </dependency>

    <!-- iTextPDF (com.lowagie 版本,用于兼容 Flying Saucer) -->
    <dependency>
        <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
        <version>2.1.7</version>
    </dependency>
</dependencies>

注意:Flying Saucer 使用的是舊版 iText 庫 com.lowagie,而不是新版 com.itextpdf,確保使用正確版本以避免依賴沖突。

二、創(chuàng)建 Thymeleaf 模板

新建一個 HTML 模板用于生成發(fā)票內(nèi)容,例如在 resources/templates/pdf/invoice.html 文件中編寫如下 HTML:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>發(fā)票</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { text-align: center; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .total { font-weight: bold; }
        .footer { margin-top: 30px; text-align: center; font-size: 12px; color: #888; }
    </style>
</head>
<body>
<h1>發(fā)票</h1>
<p>發(fā)票編號:<span th:text="${invoiceNumber}"></span></p>
<p>開具日期:<span th:text="${invoiceDate}"></span></p>
<p>買家姓名:<span th:text="${buyerName}"></span></p>

<h2>商品詳情</h2>
<table>
    <thead>
    <tr>
        <th>商品名稱</th>
        <th>描述</th>
        <th>數(shù)量</th>
        <th>單價</th>
        <th>小計</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="item : ${goodsItems}">
        <td th:text="${item.goodsName}"></td>
        <td th:text="${item.goodsDesc}"></td>
        <td th:text="${item.quantity}"></td>
        <td th:text="${item.unitPrice}"></td>
        <td th:text="${item.totalPrice}"></td>
    </tr>
    </tbody>
</table>

<p class="total">總金額:<span th:text="${finalAmount}"></span></p>
<div class="footer">感謝您的購買!</div>
</body>
</html>

三、創(chuàng)建 PDF 生成工具類

接下來,創(chuàng)建 PdfUtil 工具類,通過 Thymeleaf 渲染 HTML 并使用 Flying Saucer 將 HTML 轉(zhuǎn)為 PDF:

package com.xyh.transaction.utils;

import com.xyh.transaction.entity.dto.goods.GoodsInvoice;
import com.xyh.transaction.exception.BusinessException;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class PdfUtil {

    public static byte[] generateInvoicePdf(String buyerName, String invoiceNumber,
                                            List<GoodsInvoice> goodsItems, String finalAmount) {
        TemplateEngine templateEngine = new TemplateEngine();

        // 使用 Thymeleaf 渲染 HTML
        Context context = new Context();
        context.setVariable("buyerName", buyerName);
        context.setVariable("invoiceNumber", invoiceNumber);
        context.setVariable("goodsItems", goodsItems);
        context.setVariable("finalAmount", finalAmount);
        String htmlContent = templateEngine.process("pdf/invoice.html", context);

        // 將 HTML 轉(zhuǎn)換為 PDF
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.getFontResolver().addFont("/path/to/your/font/simhei.ttf", true); // 防止中文亂碼
            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            renderer.createPDF(outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("發(fā)票PDF 生成失敗");
        }
    }
}

四、在 Spring Boot 中使用 PDF 生成功能

在 Spring Boot 控制器中調(diào)用 PdfUtil.generateInvoicePdf,將生成的 PDF 返回給用戶或作為附件發(fā)送郵件:

@RestController
@RequestMapping("/invoice")
public class InvoiceController {

    @GetMapping("/generate")
    public ResponseEntity<byte[]> generateInvoice() {
        byte[] pdfBytes = PdfUtil.generateInvoicePdf("張三", "INV-12345",
                goodsItems, "1000.00");
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "invoice.pdf");
        
        return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
    }
}

五、常見錯誤及解決方案

1. 中文字符亂碼

  • 問題:生成的 PDF 中,中文字符可能出現(xiàn)亂碼。
  • 解決方案:確保 addFont 引用支持中文的字體文件(如 simhei.ttf)。

2. 圖片加載失敗

  • 問題:HTML 中的圖片在 PDF 中無法正常顯示。

  • 解決方案:將圖片路徑設(shè)置為絕對路徑或通過 setBaseURL 指定資源根路徑:

renderer.getSharedContext().setBaseURL("file:/path/to/resources/");

3. 樣式不生效

  • 問題:Flying Saucer 不支持高級 CSS。
  • 解決方案:使用基本的 table 布局和簡單 CSS,不依賴 flex、CSS 變量等。

4. 模板路徑識別錯誤

  • 問題:模板引擎找不到指定 HTML 文件。
  • 解決方案:檢查文件路徑和模板配置,確保模板放置在 resources/templates/pdf 目錄下。

5. 依賴沖突

  • 問題:Flying Saucer 使用舊版 iText,與其他依賴產(chǎn)生沖突。
  • 解決方案:獨立模塊管理依賴,使用 maven-shade-plugin 處理沖突類。

6. 內(nèi)存不足

  • 問題:生成大型 PDF 時出現(xiàn)內(nèi)存溢出。
  • 解決方案:增加 JVM 內(nèi)存配置,或簡化 HTML 結(jié)構(gòu)降低內(nèi)存占用。

總結(jié)

使用 Spring Boot 集成 Thymeleaf 和 Flying Saucer 實現(xiàn) PDF 導(dǎo)出是生成發(fā)票、報告等文檔的高效方式。通過以上實現(xiàn)步驟和常見問題解決方案,希望可以幫助您順利在項目中集成此功能。

以上就是使用SpringBoot集成Thymeleaf和Flying Saucer實現(xiàn)PDF導(dǎo)出的詳細內(nèi)容,更多關(guān)于SpringBoot實現(xiàn)PDF導(dǎo)出的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

岳西县| 环江| 南平市| 四川省| 凤凰县| 麻城市| 图木舒克市| 安义县| 贵溪市| 白河县| 兴文县| 秀山| 嘉祥县| 临沧市| 奉新县| 宜君县| 德令哈市| 泗水县| 车险| 建宁县| 南江县| 清远市| 洮南市| 灵武市| 苍山县| 唐山市| 黄大仙区| 清水县| 清徐县| 罗田县| 图们市| 清水河县| 凌源市| 遂溪县| 中阳县| 山东省| 松江区| 鹤庆县| 宜兰市| 建德市| 乃东县|