Spring Boot集成itext实现html生成PDF功能
liuian 2024-12-04 13:46 20 浏览
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;
}
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
- https://github.com/Harries/springboot-demo
3.测试
- 启动spring boot应用
- 访问http://127.0.0.1:8088/orders/
- 访问http://127.0.0.1:8088/orders/pdf,生成pdf并下载
4.引用
- https://springhow.com/spring-boot-pdf-generation/
- https://kb.itextpdf.com/itext/ebooks
- http://www.liuhaihua.cn/archives/710362.html
相关推荐
- GANs为何引爆机器学习?这篇基于TensorFlow的实例教程为你解惑!
-
「机器人圈导览」:生成对抗网络无疑是机器学习领域近三年来最火爆的研究领域,相关论文层出不求,各种领域的应用层出不穷。那么,GAN到底如何实践?本文编译自Medium,该文作者以一朵玫瑰花为例,详细阐...
- 高丽大学等机构联合发布StarGAN:可自定义表情和面部特征
-
原文来源:arXiv、GitHub作者:YunjeyChoi、MinjeChoi、MunyoungKim、Jung-WooHa、SungKim、JaegulChoo「雷克世界」编译:嗯~...
- TensorFlow和PyTorch相继发布最新版,有何变化
-
原文来源:GitHub「机器人圈」编译:嗯~阿童木呀、多啦A亮Tensorflow主要特征和改进在Tensorflow库中添加封装评估量。所添加的评估量列表如下:1.深度神经网络分类器(DNNCl...
- 「2022 年」崔庆才 Python3 爬虫教程 - 深度学习识别滑动验证码缺口
-
上一节我们使用OpenCV识别了图形验证码躯壳欧。这时候就有朋友可能会说了,现在深度学习不是对图像识别很准吗?那深度学习可以用在识别滑动验证码缺口位置吗?当然也是可以的,本节我们就来了解下使用深度...
- 20K star!搞定 LLM 微调的开源利器
-
LLM(大语言模型)微调一直都是老大难问题,不仅因为微调需要大量的计算资源,而且微调的方法也很多,要去尝试每种方法的效果,需要安装大量的第三方库和依赖,甚至要接入一些框架,可能在还没开始微调就已经因为...
- 大模型DeepSeek本地部署后如何进行自定义调整?
-
1.理解模型架构a)查看深度求索官方文档或提供的源代码文件,了解模型的结构、输入输出格式以及支持的功能。模型是否为预训练权重?如果是,可以在预训练的基础上进行微调(Fine-tuning)。是否需要...
- 因配置不当,约5000个AI模型与数据集在公网暴露
-
除了可访问机器学习模型外,暴露的数据还可能包括训练数据集、超参数,甚至是用于构建模型的原始数据。前情回顾·人工智能安全动态向ChatGPT植入恶意“长期记忆”,持续窃取用户输入数据多模态大语言模型的致...
- 基于pytorch的深度学习人员重识别
-
基于pytorch的深度学习人员重识别Torchreid是一个库。基于pytorch的深度学习人员重识别。特点:支持多GPU训练支持图像的人员重识别与视频的人员重识别端到端的训练与评估简单的re...
- DeepSeek本地部署:轻松训练你的AI模型
-
引言:为什么选择本地部署?在AI技术飞速发展的今天,越来越多的企业和个人希望将AI技术应用于实际场景中。然而,对于一些对数据隐私和计算资源有特殊需求的用户来说,云端部署可能并不是最佳选择。此时,本地部...
- 谷歌今天又开源了,这次是Sketch-RNN
-
前不久,谷歌公布了一项最新技术,可以教机器画画。今天,谷歌开源了代码。在我们研究其代码之前,首先先按要求设置Magenta环境。(https://github.com/tensorflow/magen...
- Tensorflow 使用预训练模型训练的完整流程
-
前面已经介绍了深度学习框架Tensorflow的图像的标注和训练数据的准备工作,本文介绍一下使用预训练模型完成训练并导出训练的模型。1.选择预训练模型1.1下载预训练模型首先需要在Tensorf...
- 30天大模型调优学习计划(30分钟训练大模型)
-
30天大模型调优学习计划,结合Unsloth和Lora进行大模型微调,掌握大模型基础知识和调优方法,熟练应用。第1周:基础入门目标:了解大模型基础并熟悉Unsloth等工具的基本使用。Day1:大模...
- python爬取喜马拉雅音频,json参数解析
-
一.抓包分析json,获取加密方式1.抓包获取音频界面f12打开抓包工具,播放一个(非vip)视频,点击“媒体”单击打开可以复制URL,发现就是我们要的音频。复制“CKwRIJEEXn-cABa0Tg...
- 五、JSONPath使用(Python)(json数据python)
-
1.安装方法pipinstalljsonpath2.jsonpath与Xpath下面表格是jsonpath语法与Xpath的完整概述和比较。Xpathjsonpath概述/$根节点.@当前节点...
- Python网络爬虫的时候json=就是让你少写个json.dumps()
-
大家好,我是皮皮。一、前言前几天在Python白银交流群【空翼】问了一个Python网络爬虫的问题,提问截图如下:登录请求地址是这个:二、实现过程这里【甯同学】给了一个提示,如下所示:估计很多小伙伴和...
- 一周热门
-
-
Python实现人事自动打卡,再也不会被批评
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
python使用fitz模块提取pdf中的图片
-
《人人译客》如何规划你的移动电商网站(2)
-
Jupyterhub安装教程 jupyter怎么安装包
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- table.render (33)
- uniapp textarea (33)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- react-admin (33)
- vscode切换git分支 (35)
- vscode美化代码 (33)
- python bytes转16进制 (35)