1.itext介绍
itext是著名的开放源码的站点sourceforge一个项目,是用于生成pdf文档的一个java类库。通过itext不仅可以生成pdf或rtf的文档,而且可以将xml、html文件转化为pdf文件
itext 的特点
以下是 itext 库的显着特点 −
- interactive − itext 为你提供类(api)来生成交互式 pdf 文档。使用这些,你可以创建地图和书籍。
- 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 程序创建新的 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 这样的静态资源将无法找到
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 带有模板引擎,可以提供动态的 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的资料请关注代码网其它相关文章!
发表评论