SpringBoot集成itext實現(xiàn)html轉(zhuǎn)PDF
1.itext介紹
iText是著名的開放源碼的站點sourceforge一個項目,是用于生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉(zhuǎn)化為PDF文件
iText 的特點
以下是 iText 庫的顯著特點 −
- Interactive − iText 為你提供類(API)來生成交互式 PDF 文檔。使用這些,你可以創(chuàng)建地圖和書籍。
- Adding bookmarks, page numbers, etc − 使用 iText,你可以添加書簽、頁碼和水印。
- Split & Merge − 使用 iText,你可以將現(xiàn)有的 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.代碼工程
實驗?zāi)繕?biāo):將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 內(nèi)容。 我們可以通過以下方法輕松將這些回復(fù)轉(zhuǎn)換為 PDF 格式。 在本例中,我導(dǎo)入了 spring-boot-starter-web 和 spring-boot-starter-thymeleaf 來為我的 spring boot 項目提供 MVC 和 thymeleaf 支持。 您可以使用自己選擇的模板引擎。 看看下面這個thymeleaf模板內(nèi)容。 主要展示訂單詳細信息。 另外,通過 OrderHelper 的輔助方法來生成一些虛擬訂單內(nèi)容。
<!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;
}
以上只是一些關(guān)鍵代碼,所有代碼請參見下面代碼倉庫
代碼倉庫
github.com/Harries/springboot-demo
3.測試
啟動spring boot應(yīng)用
訪問http://127.0.0.1:8088/orders/

訪問http://127.0.0.1:8088/orders/pdf,生成pdf并下載
以上就是SpringBoot集成itext實現(xiàn)html轉(zhuǎn)PDF的詳細內(nèi)容,更多關(guān)于SpringBoot itext實現(xiàn)html轉(zhuǎn)PDF的資料請關(guān)注腳本之家其它相關(guān)文章!
- Springboot整合itext實現(xiàn)PDF文件合并
- SpringBoot3集成iText實現(xiàn)PDF導(dǎo)出功能
- SpringBoot集成iTextPDF的實例
- SpringBoot整合iText7導(dǎo)出PDF及性能優(yōu)化方式
- SpringBoot使用itext填充pdf表單及導(dǎo)出pdf的流程
- SpringBoot集成itextpdf實現(xiàn)根據(jù)模板動態(tài)生成PDF
- SpringBoot使用iText7實現(xiàn)將HTML轉(zhuǎn)成PDF并添加頁眉頁腳水印
- SpringBoot集成itext導(dǎo)出PDF的過程
相關(guān)文章
Java實現(xiàn)紀元秒和本地日期時間互換的方法【經(jīng)典實例】
這篇文章主要介紹了Java實現(xiàn)紀元秒和本地日期時間互換的方法,結(jié)合具體實例形式分析了Java日期時間相關(guān)操作技巧,需要的朋友可以參考下2017-04-04
Java的MyBatis框架中對數(shù)據(jù)庫進行動態(tài)SQL查詢的教程
這篇文章主要介紹了Java的MyBatis框架中對數(shù)據(jù)庫進行動態(tài)SQL查詢的教程,講解了MyBatis中一些控制查詢流程的常用語句,需要的朋友可以參考下2016-04-04
Java使用Calendar類實現(xiàn)動態(tài)日歷
這篇文章主要為大家詳細介紹了Java使用Calendar類實現(xiàn)動態(tài)日歷,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07

