欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot集成itext實現html轉PDF

 更新時間:2024年03月28日 15:07:15   作者:HBLOG  
iText是著名的開放源碼的站點sourceforge一個項目,是用于生成PDF文檔的一個java類庫,本文主要介紹了如何利用itext實現html轉PDF,需要的可以參考下

1.itext介紹

iText是著名的開放源碼的站點sourceforge一個項目,是用于生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件

iText 的特點

以下是 iText 庫的顯著特點 −

  • Interactive − iText 為你提供類(API)來生成交互式 PDF 文檔。使用這些,你可以創(chuàng)建地圖和書籍。
  • Adding bookmarks, page numbers, etc − 使用 iText,你可以添加書簽、頁碼和水印。
  • Split & Merge − 使用 iText,你可以將現有的 PDF 拆分為多個 PDF,還可以向其中添加/連接其他頁面。
  • Fill Forms − 使用 iText,你可以在 PDF 文檔中填寫交互式表單。
  • Save as Image − 使用 iText,你可以將 PDF 保存為圖像文件,例如 PNG 或 JPEG。
  • Canvas − iText 庫為您提供了一個 Canvas 類,你可以使用它在 PDF 文檔上繪制各種幾何形狀,如圓形、線條等。
  • Create PDFs − 使用 iText,你可以從 Java 程序創(chuàng)建新的 PDF 文件。你也可以包含圖像和字體。

2.代碼工程

實驗目標:將thymeleaf 的views生成成PDF

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>itextpdf</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

application.yaml

server:
  port: 8088
spring:
  thymeleaf:
    cache: false

DemoApplication

package com.et.itextpdf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan
@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

controller

converterProperties.setBaseUri 很重要。 否則,像 /main.css 這樣的靜態(tài)資源將無法找到

package com.et.itextpdf.controller;

import com.et.itextpdf.pojo.Order;
import com.et.itextpdf.util.OrderHelper;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/orders")
public class PDFController {


    @Autowired
    ServletContext servletContext;

    private final TemplateEngine templateEngine;

    public PDFController(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    @RequestMapping(path = "/")
    public String getOrderPage(Model model) {
        Order order = OrderHelper.getOrder();
        model.addAttribute("orderEntry", order);
        return "order";
    }

    @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();
        ConverterProperties converterProperties = new ConverterProperties();
        converterProperties.setBaseUri("http://localhost:8088");
        /* 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()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=order.pdf")
                .contentType(MediaType.APPLICATION_PDF)
                .body(bytes);

    }

}

view

Spring MVC 帶有模板引擎,可以提供動態(tài)的 HTML 內容。 我們可以通過以下方法輕松將這些回復轉換為 PDF 格式。 在本例中,我導入了 spring-boot-starter-web 和 spring-boot-starter-thymeleaf 來為我的 spring boot 項目提供 MVC 和 thymeleaf 支持。 您可以使用自己選擇的模板引擎。 看看下面這個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>

POJO

package com.et.itextpdf.pojo;

import lombok.Data;

@Data
public class Account {
    private String name;
    private String phoneNumber;
    private String email;
    private Address address;


}

package com.et.itextpdf.pojo;

import lombok.Data;

@Data
public class Address {
    private String street;
    private String city;
    private String state;
    private String zipCode;
}

package com.et.itextpdf.pojo;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Item {
    private String sku;
    private String name;
    private Integer quantity;
    private BigDecimal price;
}

package com.et.itextpdf.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Order {
    private Integer orderId;
    private String date;
    private Account account;
    private Payment payment;
    private List<Item> items;
}

package com.et.itextpdf.pojo;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Payment {
    private BigDecimal amount;
    private String cardNumber;
    private String cvv;
    private String month;
    private String year;
}

以上只是一些關鍵代碼,所有代碼請參見下面代碼倉庫

代碼倉庫

github.com/Harries/springboot-demo

3.測試

啟動spring boot應用

訪問http://127.0.0.1:8088/orders/

訪問http://127.0.0.1:8088/orders/pdf,生成pdf并下載

以上就是SpringBoot集成itext實現html轉PDF的詳細內容,更多關于SpringBoot itext實現html轉PDF的資料請關注腳本之家其它相關文章!

相關文章

  • Java實現紀元秒和本地日期時間互換的方法【經典實例】

    Java實現紀元秒和本地日期時間互換的方法【經典實例】

    這篇文章主要介紹了Java實現紀元秒和本地日期時間互換的方法,結合具體實例形式分析了Java日期時間相關操作技巧,需要的朋友可以參考下
    2017-04-04
  • Mybatis 傳輸List的實現代碼

    Mybatis 傳輸List的實現代碼

    本文通過實例代碼給大家介紹了mybatis傳輸list的實現代碼,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
    2017-09-09
  • Java徹底消滅if-else的8種方案

    Java徹底消滅if-else的8種方案

    這篇文章主要給大家介紹了關于Java徹底消滅if-else的8種方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • Java的MyBatis框架中對數據庫進行動態(tài)SQL查詢的教程

    Java的MyBatis框架中對數據庫進行動態(tài)SQL查詢的教程

    這篇文章主要介紹了Java的MyBatis框架中對數據庫進行動態(tài)SQL查詢的教程,講解了MyBatis中一些控制查詢流程的常用語句,需要的朋友可以參考下
    2016-04-04
  • java中break和continue源碼解析

    java中break和continue源碼解析

    這篇文章主要針對java中break和continue的區(qū)別進行詳細介紹,幫助大家更好的學習了解java中break和continue源碼,感興趣的小伙伴們可以參考一下
    2016-06-06
  • Spring MVC創(chuàng)建項目踩過的bug

    Spring MVC創(chuàng)建項目踩過的bug

    這篇文章主要介紹了Spring MVC創(chuàng)建項目踩過的bug,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • Java中URL傳中文時亂碼的解決方法

    Java中URL傳中文時亂碼的解決方法

    為什么說亂碼是中國程序員無法避免的話題呢?這個主要是編碼機制上的原因,大家都知道中文和英文的編碼格式不一樣,解碼自然也不一樣!這篇文章就給大家分享了Java中URL傳中文時亂碼的解決方法,有需要的朋友們可以參考借鑒。
    2016-10-10
  • Spring Security自定義失敗處理器問題

    Spring Security自定義失敗處理器問題

    這篇文章主要介紹了Spring Security自定義失敗處理器問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Java使用Calendar類實現動態(tài)日歷

    Java使用Calendar類實現動態(tài)日歷

    這篇文章主要為大家詳細介紹了Java使用Calendar類實現動態(tài)日歷,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Maven項目修改JDK版本全過程

    Maven項目修改JDK版本全過程

    這篇文章主要介紹了Maven項目修改JDK版本全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03

最新評論