国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)

這篇具有很好參考價值的文章主要介紹了SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)

1. 前言

近期在項目種遇到了實時生成復雜 PDF 的需求,經過一番調研和測試,最終選擇了采用 Thymeleaf 和 iText7 來實現需求,本文將詳細介紹實現過程。

2. 技術思路

  1. 通過 Thymeleaf 渲染生成需要的頁面內容;
  2. 通過 iText7 html2pdf 庫將 Thymeleaf 渲染的結果轉換成 PDF;
  3. 將 PDF 內容寫入到接口輸出流中返回給前端瀏覽器展示;

3. 實現過程

  1. Maven 引入依賴;

    <!-- Thymeleaf -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    <!-- iText html2pdf -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>html2pdf</artifactId>
        <version>5.0.0</version>
    </dependency>
    
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    
    <!-- 獲取資源文件 -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.21</version>
    </dependency>
    
  2. 編寫 Thymeleaf 模板 resources/templates/demo.html

    <!DOCTYPE html>
    <html lang="zh">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>PDF Demo</title>
    
        <style>
            body {
                padding-top: 50px;
                padding-left: 60px;
                padding-right: 60px;
                font-family: 'KaiTi', serif;
            }
    
            .title {
                color: red;
                text-align: center;
                margin-bottom: 50px;
            }
    
            table {
                width: 100%;
                border: 1px solid black;
                border-spacing: 0;
            }
    
            th {
                border: 1px solid black;
                background-color: rgb(128, 128, 128);
            }
    
            td {
                border: 1px solid black;
            }
        </style>
    </head>
    
    <body>
    <h1 class="title" th:text="${title}"></h1>
    
    <table>
        <thead>
        <tr>
            <th>序號</th>
            <th>姓名</th>
            <th>年齡</th>
            <th>性別</th>
        </tr>
        </thead>
        <tbody th:each="student, studentStat : ${students}">
        <tr>
            <td th:text="${studentStat.count}"></td>
            <td th:text="${student.name}"></td>
            <td th:text="${student.age}"></td>
            <td th:text="${student.sex}"></td>
        </tr>
        </tbody>
    </table>
    
    </body>
    </html>
    
  3. 添加中文字體資源 resources/fonts/simkai.ttf;

  4. 編寫 PDF 頁碼事件處理 handler/PageEventHandler

    package com.xiaoqqya.itextpdf.handler;
    
    import com.itextpdf.kernel.events.Event;
    import com.itextpdf.kernel.events.IEventHandler;
    import com.itextpdf.kernel.events.PdfDocumentEvent;
    import com.itextpdf.kernel.geom.Rectangle;
    import com.itextpdf.kernel.pdf.PdfDocument;
    import com.itextpdf.kernel.pdf.PdfPage;
    import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
    import com.itextpdf.layout.Canvas;
    import com.itextpdf.layout.element.Paragraph;
    import com.itextpdf.layout.properties.TextAlignment;
    
    /**
     * 頁碼事件處理.
     *
     * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
     * @since 2023/08/29
     */
    public class PageEventHandler implements IEventHandler {
    
        @Override
        public void handleEvent(Event event) {
            PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
            PdfDocument document = documentEvent.getDocument();
            PdfPage page = documentEvent.getPage();
            Rectangle pageSize = page.getPageSize();
    
            PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), document);
            Canvas canvas = new Canvas(pdfCanvas, pageSize);
            float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
            float y = pageSize.getBottom() + 15;
            Paragraph paragraph = new Paragraph("-- " + document.getPageNumber(page) + " --")
                    .setFontSize(10);
            canvas.showTextAligned(paragraph, x, y, TextAlignment.CENTER);
            canvas.close();
        }
    }
    
  5. 編寫 Student 實體類 model/domain/Student

    package com.xiaoqqya.itextpdf.model.domain;
    
    import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * 學生.
     *
     * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
     * @since 2023/08/29
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public class Student {
    
        /**
         * 姓名
         */
        private String name;
    
        /**
         * 、
         * 年齡
         */
        private Integer age;
    
        /**
         * 性別
         */
        private String sex;
    }
    
  6. 編寫 Service service/PdfService 生成 PDF;

    package com.xiaoqqya.itextpdf.service.impl;
    
    import cn.hutool.core.io.resource.ResourceUtil;
    import com.itextpdf.html2pdf.ConverterProperties;
    import com.itextpdf.html2pdf.HtmlConverter;
    import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
    import com.itextpdf.io.font.FontProgramFactory;
    import com.itextpdf.kernel.events.PdfDocumentEvent;
    import com.itextpdf.kernel.geom.PageSize;
    import com.itextpdf.kernel.pdf.PdfDocument;
    import com.itextpdf.kernel.pdf.PdfWriter;
    import com.itextpdf.layout.font.FontProvider;
    import com.xiaoqqya.itextpdf.exception.CustomException;
    import com.xiaoqqya.itextpdf.handler.PageEventHandler;
    import com.xiaoqqya.itextpdf.model.domain.Student;
    import com.xiaoqqya.itextpdf.service.PdfService;
    import org.springframework.stereotype.Service;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    import javax.annotation.Resource;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * PDF Service.
     *
     * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
     * @since 2023/08/29
     */
    @Service
    public class PdfServiceImpl implements PdfService {
    
        @Resource
        private TemplateEngine templateEngine;
    
        /**
         * 生成 PDF.
         *
         * @param outputStream 輸出流
         */
        @Override
        public void generatePdf(OutputStream outputStream) {
            // 模擬數據
            List<Student> students = new ArrayList<>();
            students.add(Student.builder().name("小紅").age(18).sex("女").build());
            students.add(Student.builder().name("小強").age(21).sex("男").build());
            students.add(Student.builder().name("熊大").age(19).sex("男").build());
    
            // 生成 Thymeleaf 上下文
            Context context = new Context();
            context.setVariable("title", "PDF Demo");
            context.setVariable("students", students);
            String demo = templateEngine.process("demo", context);
    
            // 生成 PDF, 并添加頁碼
            try (PdfWriter pdfWriter = new PdfWriter(outputStream); PdfDocument pdfDocument = new PdfDocument(pdfWriter)) {
                pdfDocument.setDefaultPageSize(PageSize.A4);
                pdfDocument.addEventHandler(PdfDocumentEvent.INSERT_PAGE, new PageEventHandler());
    
                ConverterProperties converterProperties = new ConverterProperties();
                FontProvider fontProvider = new DefaultFontProvider(true, true, false);
                fontProvider.addFont(FontProgramFactory.createFont(ResourceUtil.readBytes("fonts/simkai.ttf")));
                converterProperties.setFontProvider(fontProvider);
                HtmlConverter.convertToPdf(demo, pdfDocument, converterProperties);
            } catch (IOException e) {
                throw new CustomException(e.getMessage());
            }
        }
    }
    
  7. 編寫 Controller controller/PdfController 返回給前端瀏覽器展示;

    package com.xiaoqqya.itextpdf.controller;
    
    import com.xiaoqqya.itextpdf.service.PdfService;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * PDF Controller.
     *
     * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
     * @since 2023/08/29
     */
    @RestController
    @RequestMapping(value = "/pdf")
    public class PdfController {
    
        @Resource
        private PdfService pdfService;
    
        /**
         * 生成 PDF.
         */
        @GetMapping
        public void generatePdf(HttpServletResponse response) throws IOException {
            pdfService.generatePdf(response.getOutputStream());
        }
    }
    

4. 測試

瀏覽器訪問 http://localhost:8080/pdf 查看效果。

參考文章:文章來源地址http://www.zghlxwxcb.cn/news/detail-688510.html

  • 使用itext7將HTML轉為pdf · Issue #12 · ydq/blog (github.com);

到了這里,關于SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 記錄使用iText7查找PDF內容關鍵字坐標,加蓋電子簽名、印章

    記錄使用iText7查找PDF內容關鍵字坐標,加蓋電子簽名、印章

    項目以前簽字都是由C端那邊進行合成操作,最近項目要求把那塊功能,由后端進行實現,其中包含坐標、、任意位置進行簽字操作,坐標是最容易實現的,曾經也寫過類似的功能在(添加圖片印章到PDF)直接復用就可以了 為了實現位置簽字,在網上查找了挺多

    2024年02月07日
    瀏覽(96)
  • SpringBoot Thymeleaf企業(yè)級真實應用:使用Flying Saucer結合iText5將HTML界面數據轉換為PDF輸出(四) 表格中斷問題

    SpringBoot Thymeleaf企業(yè)級真實應用:使用Flying Saucer結合iText5將HTML界面數據轉換為PDF輸出(四) 表格中斷問題

    接上一篇 SpringBoot Thymeleaf企業(yè)級真實應用:使用Flying Saucer結合iText5將HTML界面數據轉換為PDF輸出(三) 給pdf加水印、頁眉頁腳、頁眉logo 設置表格的css樣式

    2024年02月12日
    瀏覽(23)
  • 【Java】使用iText生成PDF文件

    【Java】使用iText生成PDF文件

    iText介紹 iText是著名的開放源碼的站點sourceforge一個項目,是用于生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。 項目要使用iText,必須引入jar包。才能使用,maven依賴如下: 輸出中文,還要引入下面itext-asian.jar包: ?

    2024年02月10日
    瀏覽(18)
  • Java中Itext生成Pdf,并給PdfCell添加圖片
  • Java XPath 使用(2023/08/29)

    眾所周知,Java 語言適合應用于 Web 開發(fā)領域,不擅長用來編寫爬蟲。但在 Web 開發(fā)過程中有時又存在爬取數據的需求,此時采用其它語言編寫獨立爬蟲模塊的話存在維護不方便的問題,所以此處筆者選擇了使用 Java + XPath 實現簡單的爬蟲功能,如果爬蟲需求較多且復雜還是推

    2024年02月10日
    瀏覽(25)
  • 【Java】itext 實現 html根據模板生成pdf 中文不顯示/圖片不顯示問題解決

    【Java】itext 實現 html根據模板生成pdf 中文不顯示/圖片不顯示問題解決

    工作中需要使用生成pdf記錄,選取使用的是itext 生成 pdf方式。分享下實現方式及遇到的問題。 這里隨便找個html課程表作為示例,添加了幾張圖片為了展示圖片轉pdf功能。 一:引入jar包 二:導入ftl文件 這塊使用的是html語法,將文件后綴名改為ftl即可,在需要參數的地方通過

    2024年02月05日
    瀏覽(24)
  • Itext生成pdf文件,html轉pdf時中文一直顯示不出來

    Itext生成pdf文件,html轉pdf時中文一直顯示不出來

    嘗試好多種方式,最后可能是跟字體有關系 字體設置為C:/Windows/Fonts/simhei.ttf? 黑體,同時html頁面上樣式要添加 pdf生成方式參考項目:E:myfilesprojectgithubdemo-html2pdf 字體問題參考文章:https://blog.51cto.com/u_15127651/4527950 最后完美解決字體問題??!

    2024年02月20日
    瀏覽(19)
  • 行業(yè)追蹤,2023-08-29

    行業(yè)追蹤,2023-08-29

    凡所有相,皆是虛妄。若見諸相非相,即見如來。 k 線圖是最好的老師,每天持續(xù)發(fā)布板塊的rps排名,追蹤板塊,板塊來開倉,板塊去清倉,丟棄自以為是的想法,板塊去留讓市場來告訴你 跟蹤板塊總結: 成交額超過 100 億 排名靠前,macd柱由綠轉紅 成交量要大于均線 有必

    2024年02月10日
    瀏覽(17)
  • 2023-08-29力扣每日一題

    鏈接: 823. 帶因子的二叉樹 題意: 用給的數字建二叉樹,要求父節(jié)點是子節(jié)點的乘積 解: 樂了 1500ms+30MB //注釋版120ms+18MB 實際代碼: 限制: 1 = arr.length = 1000 2 = arr[i] = 109 arr 中的所有值 互不相同

    2024年02月11日
    瀏覽(24)
  • 2023-08-29 LeetCode(帶因子的二叉樹)

    2023-08-29 LeetCode(帶因子的二叉樹)

    點擊跳轉到題目位置 給出一個含有不重復整數元素的數組 arr ,每個整數 arr[i] 均大于 1。 用這些整數來構建二叉樹,每個整數可以使用任意次數。其中:每個非葉結點的值應等于它的兩個子結點的值的乘積。 滿足條件的二叉樹一共有多少個?答案可能很大,返回 對 109 + 7

    2024年02月10日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包