SpringBoot集成itext實(shí)現(xiàn)html轉(zhuǎn)PDF
1.itext介紹
iText是著名的開(kāi)放源碼的站點(diǎn)sourceforge一個(gè)項(xiàng)目,是用于生成PDF文檔的一個(gè)java類(lèi)庫(kù)。通過(guò)iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉(zhuǎn)化為PDF文件
iText 的特點(diǎn)
以下是 iText 庫(kù)的顯著特點(diǎn) −
- Interactive − iText 為你提供類(lèi)(API)來(lái)生成交互式 PDF 文檔。使用這些,你可以創(chuàng)建地圖和書(shū)籍。
- Adding bookmarks, page numbers, etc − 使用 iText,你可以添加書(shū)簽、頁(yè)碼和水印。
- Split & Merge − 使用 iText,你可以將現(xiàn)有的 PDF 拆分為多個(gè) PDF,還可以向其中添加/連接其他頁(yè)面。
- Fill Forms − 使用 iText,你可以在 PDF 文檔中填寫(xiě)交互式表單。
- Save as Image − 使用 iText,你可以將 PDF 保存為圖像文件,例如 PNG 或 JPEG。
- Canvas − iText 庫(kù)為您提供了一個(gè) Canvas 類(lèi),你可以使用它在 PDF 文檔上繪制各種幾何形狀,如圓形、線條等。
- Create PDFs − 使用 iText,你可以從 Java 程序創(chuàng)建新的 PDF 文件。你也可以包含圖像和字體。
2.代碼工程
實(shí)驗(yàn)?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)資源將無(wú)法找到
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 帶有模板引擎,可以提供動(dòng)態(tài)的 HTML 內(nèi)容。 我們可以通過(guò)以下方法輕松將這些回復(fù)轉(zhuǎn)換為 PDF 格式。 在本例中,我導(dǎo)入了 spring-boot-starter-web 和 spring-boot-starter-thymeleaf 來(lái)為我的 spring boot 項(xiàng)目提供 MVC 和 thymeleaf 支持。 您可以使用自己選擇的模板引擎。 看看下面這個(gè)thymeleaf模板內(nèi)容。 主要展示訂單詳細(xì)信息。 另外,通過(guò) OrderHelper 的輔助方法來(lái)生成一些虛擬訂單內(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)鍵代碼,所有代碼請(qǐng)參見(jiàn)下面代碼倉(cāng)庫(kù)
代碼倉(cāng)庫(kù)
github.com/Harries/springboot-demo
3.測(cè)試
啟動(dòng)spring boot應(yīng)用
訪問(wèn)http://127.0.0.1:8088/orders/
訪問(wèn)http://127.0.0.1:8088/orders/pdf
,生成pdf并下載
以上就是SpringBoot集成itext實(shí)現(xiàn)html轉(zhuǎn)PDF的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot itext實(shí)現(xiàn)html轉(zhuǎn)PDF的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Springboot整合itext實(shí)現(xiàn)PDF文件合并
- SpringBoot3集成iText實(shí)現(xiàn)PDF導(dǎo)出功能
- SpringBoot集成iTextPDF的實(shí)例
- SpringBoot整合iText7導(dǎo)出PDF及性能優(yōu)化方式
- SpringBoot使用itext填充pdf表單及導(dǎo)出pdf的流程
- SpringBoot集成itextpdf實(shí)現(xiàn)根據(jù)模板動(dòng)態(tài)生成PDF
- SpringBoot使用iText7實(shí)現(xiàn)將HTML轉(zhuǎn)成PDF并添加頁(yè)眉頁(yè)腳水印
- SpringBoot集成itext導(dǎo)出PDF的過(guò)程
相關(guān)文章
Java實(shí)現(xiàn)紀(jì)元秒和本地日期時(shí)間互換的方法【經(jīng)典實(shí)例】
這篇文章主要介紹了Java實(shí)現(xiàn)紀(jì)元秒和本地日期時(shí)間互換的方法,結(jié)合具體實(shí)例形式分析了Java日期時(shí)間相關(guān)操作技巧,需要的朋友可以參考下2017-04-04Mybatis 傳輸List的實(shí)現(xiàn)代碼
本文通過(guò)實(shí)例代碼給大家介紹了mybatis傳輸list的實(shí)現(xiàn)代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-09-09Java的MyBatis框架中對(duì)數(shù)據(jù)庫(kù)進(jìn)行動(dòng)態(tài)SQL查詢(xún)的教程
這篇文章主要介紹了Java的MyBatis框架中對(duì)數(shù)據(jù)庫(kù)進(jìn)行動(dòng)態(tài)SQL查詢(xún)的教程,講解了MyBatis中一些控制查詢(xún)流程的常用語(yǔ)句,需要的朋友可以參考下2016-04-04Spring MVC創(chuàng)建項(xiàng)目踩過(guò)的bug
這篇文章主要介紹了Spring MVC創(chuàng)建項(xiàng)目踩過(guò)的bug,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11Spring Security自定義失敗處理器問(wèn)題
這篇文章主要介紹了Spring Security自定義失敗處理器問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08Java使用Calendar類(lèi)實(shí)現(xiàn)動(dòng)態(tài)日歷
這篇文章主要為大家詳細(xì)介紹了Java使用Calendar類(lèi)實(shí)現(xiàn)動(dòng)態(tài)日歷,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07