java集成itextpdf实现通过pdf模板填充数据生成pdf

2023-10-08 11:40

本文主要是介绍java集成itextpdf实现通过pdf模板填充数据生成pdf,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一、制作pdf模板
    • 1.1、使用excel制作一个表格
    • 1.2、转成pdf
    • 1.3、设置表单域
    • 1.4、最终模版效果
  • 二、引入POM依赖
  • 三、代码实现
    • 3.1、工具类
    • 3.2、实体对象
    • 3.3、Controller


一、制作pdf模板

1.1、使用excel制作一个表格

在这里插入图片描述

1.2、转成pdf

我采用的是pdfelement 官网地址需要付费或者自行破解,也可以使用其他pdf编辑器。

在这里插入图片描述

1.3、设置表单域

在这里插入图片描述

1.4、最终模版效果

在这里插入图片描述

二、引入POM依赖

<!--pdf处理--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>

三、代码实现

将制作好的pdf模板放入项目resources/pdf目录下,如图

在这里插入图片描述

3.1、工具类

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ResourceUtils;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** pdf相关工具类* 注意事项:* 1、时间类型需要转成字符串* 2、只支持对象嵌对象,两层结构;对象嵌对象再嵌对象,第三层对象无法解析,如果遇到这种情况需要写成递归或解析第三次。** @author zero*/
@Slf4j
public class PdfUtil {private static boolean isPrimitiveOrWrapper(Class<?> clazz) {return clazz.isPrimitive() || clazz.getName().startsWith("java.lang");}private static Map<String, String> turnMap(Object object) {Map<String, Object> stringObjectMap = BeanUtil.beanToMap(object);Map<String, String> map = new HashMap<>(stringObjectMap.size() * 2);// 打印输出属性名称和属性值for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {String key = entry.getKey();Object value = entry.getValue();if (ObjectUtil.isNotEmpty(value)) {//基本类型和封装类型if (isPrimitiveOrWrapper(value.getClass())) {map.put(key, String.valueOf(value));} else {//其他类型if (value instanceof List) {List<Object> list = (List) value;for (int i = 0; i < list.size(); i++) {Object o = list.get(i);Map<String, Object> stringObjectMap1 = BeanUtil.beanToMap(o);for (Map.Entry<String, Object> entry1 : stringObjectMap1.entrySet()) {String key1 = entry1.getKey();Object value1 = entry1.getValue();map.put(StrUtil.format("{}.{}{}", key, key1, i), String.valueOf(value1));}}} else {Map<String, Object> stringObjectMap1 = BeanUtil.beanToMap(value);for (Map.Entry<String, Object> entry1 : stringObjectMap1.entrySet()) {String key1 = entry1.getKey();Object value1 = entry1.getValue();map.put(StrUtil.format("{}.{}", key, key1), String.valueOf(value1));}}}}}return map;}public static void generatePdf(HttpServletRequest request,HttpServletResponse response,String templateName, Object object,boolean download) {try (OutputStream responseOutputStream = response.getOutputStream();ByteArrayOutputStream fileOut = new ByteArrayOutputStream()) {//模板在项目中的位置Resource resource = new PathMatchingResourcePatternResolver().getResource(ResourceUtils.CLASSPATH_URL_PREFIX + "pdf/" + templateName);PdfReader reader = new PdfReader(resource.getInputStream());PdfStamper ps = new PdfStamper(reader, fileOut);
//            BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);ArrayList<BaseFont> fontList = new ArrayList<>();fontList.add(bf);//取出报表模板中的所有字段AcroFields fields = ps.getAcroFields();fields.setSubstitutionFonts(fontList);PdfUtil.fillData(fields, PdfUtil.turnMap(object));//必须要调用这个,否则文档不会生成的  如果为false那么生成的PDF文件还能编辑,一定要设为trueps.setFormFlattening(true);ps.close();if (download) {writerFile(request, response, templateName, false);}fileOut.writeTo(responseOutputStream);} catch (Exception e) {log.error("pdf生成异常:", e);throw new RuntimeException("操作异常请联系管理员!");}}/*** 填充数据** @param fields* @param data* @throws IOException* @throws DocumentException*/private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {Map<String, AcroFields.Item> formFields = fields.getFields();for (String key : data.keySet()) {if (formFields.containsKey(key)) {String value = data.get(key);// 为字段赋值,注意字段名称是区分大小写的fields.setField(key, value);}}}/*** 写出文件** @param request* @param response* @param fileName* @param deleteOnExit 是否需要删除本地文件*/private static void writerFile(HttpServletRequest request,HttpServletResponse response,String fileName,boolean deleteOnExit) throws IOException {File file = new File("/" + fileName);file.createNewFile();response.setCharacterEncoding(request.getCharacterEncoding());response.setContentType("application/pdf");try (FileInputStream fis = new FileInputStream(file);) {//这里主要防止下载的PDF文件名乱码response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));IOUtils.copy(fis, response.getOutputStream());response.flushBuffer();if (deleteOnExit) {file.deleteOnExit();}} catch (Exception e) {log.error("pdf生成异常1:", e);throw new RuntimeException("操作异常1请联系管理员!");}}
}

3.2、实体对象


import lombok.Data;import java.util.List;/*** @author zero*/
@Data
public class TestDto {private String name;private String birthday;private Other other;private List<Other> otherList;@Datapublic static class Other {private String career;private String company;}}

3.3、Controller

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;/*** 测试 控制层** @author zero*/
@RestController
@RequestMapping("test")
@Api(tags = "测试")
public class TestController {@GetMapping("/pdf")public void pdf(HttpServletRequest request, HttpServletResponse response) {TestDto testDto = new TestDto();testDto.setName("张三");testDto.setBirthday("2020-12-12");TestDto.Other other = new TestDto.Other();other.setCareer("码农");other.setCompany("字节不跳动");testDto.setOther(other);List<TestDto.Other> list = new ArrayList<>();for (int i = 0; i <= 2; i++) {TestDto.Other other1 = new TestDto.Other();other1.setCareer("码农" + i);other1.setCompany("字节不跳动" + i);list.add(other1);}testDto.setOtherList(list);PdfUtil.generatePdf(request, response, "test.pdf", testDto, false);}}

浏览器访问ip:port/test/pdf,其中ip为你的ip地址,port为你的端口,访问结果如下:

在这里插入图片描述

这篇关于java集成itextpdf实现通过pdf模板填充数据生成pdf的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/165017

相关文章

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

Spring @RequestMapping 注解及使用技巧详解

《Spring@RequestMapping注解及使用技巧详解》@RequestMapping是SpringMVC中定义请求映射规则的核心注解,用于将HTTP请求映射到Controller处理方法... 目录一、核心作用二、关键参数说明三、快捷组合注解四、动态路径参数(@PathVariable)五、匹配请

Java -jar命令如何运行外部依赖JAR包

《Java-jar命令如何运行外部依赖JAR包》在Java应用部署中,java-jar命令是启动可执行JAR包的标准方式,但当应用需要依赖外部JAR文件时,直接使用java-jar会面临类加载困... 目录引言:外部依赖JAR的必要性一、问题本质:类加载机制的限制1. Java -jar的默认行为2. 类加

Java进程CPU使用率过高排查步骤详细讲解

《Java进程CPU使用率过高排查步骤详细讲解》:本文主要介绍Java进程CPU使用率过高排查的相关资料,针对Java进程CPU使用率高的问题,我们可以遵循以下步骤进行排查和优化,文中通过代码介绍... 目录前言一、初步定位问题1.1 确认进程状态1.2 确定Java进程ID1.3 快速生成线程堆栈二、分析

Swagger在java中的运用及常见问题解决

《Swagger在java中的运用及常见问题解决》Swagger插件是一款深受Java开发者喜爱的工具,它在前后端分离的开发模式下发挥着重要作用,:本文主要介绍Swagger在java中的运用及常... 目录前言1. Swagger 的主要功能1.1 交互式 API 文档1.2 客户端 SDK 生成1.3

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

Java中的登录技术保姆级详细教程

《Java中的登录技术保姆级详细教程》:本文主要介绍Java中登录技术保姆级详细教程的相关资料,在Java中我们可以使用各种技术和框架来实现这些功能,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录1.登录思路2.登录标记1.会话技术2.会话跟踪1.Cookie技术2.Session技术3.令牌技

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

java String.join()方法实例详解

《javaString.join()方法实例详解》String.join()是Java提供的一个实用方法,用于将多个字符串按照指定的分隔符连接成一个字符串,这一方法是Java8中引入的,极大地简化了... 目录bVARxMJava String.join() 方法详解1. 方法定义2. 基本用法2.1 拼接