java itext5 生成PDF并填充数据导出

java itext5 生成PDF并填充数据导出

主要功能有文本勾选框页眉页脚图片等功能。肯定没有专业软件画的好看,只是一点儿方法。仅供参考。

依赖

复制代码
        <!--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>

文本勾选框

生成勾选框的图片,将图片插入到文本前面

复制代码
private static Image checkBoxPng;

	static {
		ClassPathResource classPathResource = new ClassPathResource(CHECK_BOX_PATH);
		try {
			byte[] byteArray = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
			checkBoxPng = Image.getInstance(byteArray);
		} catch (IOException | BadElementException e1) {
			e1.printStackTrace();
		}
	}

-------------------------------------------------------------------------

final Paragraph paragraph = new Paragraph();
		if (checkBox != null && checkBox) {
			try {
//				final Image png = Image.getInstance(CHECK_BOX_PATH);
				// y轴 向下偏移5 保证大致上都是水平的
				final Chunk chunk = new Chunk(checkBoxPng, 0, -5);
				paragraph.add(chunk);
			} catch (Exception e) {
				throw new BusinessException(e.getMessage());
			}
		}
		paragraph.add(new Phrase(value, font));

页眉页脚

itext5没有页眉页脚设置的api,所以用的是定位 的方式;

new Document();时预留出页眉和页脚数据所需要的空间大小

pdfPTable.writeSelectedRows(); 定位的方式把表格定位到对应的位置上即可

复制代码
@Slf4j
@Component
public abstract class HeaderFooterEventHelper extends PdfPageEventHelper {
	/**
	 * 页眉
	 */
	protected final List<CustomExportTemplateModuleDTO> headerList;
	/**
	 * 页脚
	 */
	protected final List<CustomExportTemplateModuleDTO> footerList;


	public HeaderFooterEventHelper(List<CustomExportTemplateModuleDTO> headerList,
	                               List<CustomExportTemplateModuleDTO> footerList) {
		this.headerList = headerList;
		this.footerList = footerList;
	}

	/**
	 * 一页加载完成触发,写入页眉和页脚
	 */
	@Override
	public abstract void onEndPage(PdfWriter writer, Document document);
}

		//移除边距 方便设置页眉和页脚  定制页眉页脚
		Document document = new Document(PageSize.A4,
				-30 + ObjectUtils.defaultIfNull(module.getLeftMargin(), 0),
				-30 + ObjectUtils.defaultIfNull(module.getRightMargin(), 0),
				// 页眉高度 + 间隙高度  /页脚高度 - 间隙高度 (页面底部有一部分真空区域)
				headerSize + GAP_SIZE + ObjectUtils.defaultIfNull(module.getUpMargin(), 0),
				footerSize + GAP_SIZE + ObjectUtils.defaultIfNull(module.getDownMargin(), 0));

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		final PdfWriter writer = PdfWriter.getInstance(document, baos);
		// 初始化 页眉、页脚数据体
		writer.setPageEvent(new HeaderFooterEventHelper(headerDTOS, footerDTOS) {
			@Override
			public void onEndPage(PdfWriter writer, Document document) {
				final ICustomExportTemplateService customExportTemplateService = SpringContextUtil.getBean(ICustomExportTemplateService.class);
				if (customExportTemplateService != null) {
					customExportTemplateService.setPdfData(this.headerList, writer, ZERO);
					customExportTemplateService.setPdfData(this.footerList, writer, ONE);
				}
			}
		});

-------------------------------------------------------------------
@Override
	public void setPdfData(List<CustomExportTemplateModuleDTO> moduleDTOS, PdfWriter writer, Integer type) {
		float size = 0;
		final float sumSize = getSumSize(moduleDTOS);
		for (CustomExportTemplateModuleDTO item : moduleDTOS) {
			PdfPTable pdfPTable; // 创建的表格
			pdfPTable.setTotalWidth(PageSize.A4.getWidth());
			pdfPTable.setWidthPercentage(WIDTH_PERCENT);
			if (Objects.equals(type, ZERO)) {
				// 页眉 基点为 左下角0点 高度为 A4全高 - 使用高度
				pdfPTable.writeSelectedRows(0, -1, ZERO,
						PageSize.A4.getHeight() - size, writer.getDirectContent());
			} else if (Objects.equals(type, ONE)) {
				// 页脚 基点为 左下角0点 高度为 列表使用总高度 - 使用高度
				pdfPTable.writeSelectedRows(0, -1, ZERO,
						sumSize - size, writer.getDirectContent());
			}
			if (item.getLabel().equals(2)) {
				size += BigDecimal.valueOf(item.getData().size())
						.multiply(BigDecimal.valueOf(CELL_SIZE)).intValue();
			} else {
				// 默认每行高度为 25
				size += CELL_SIZE;
			}
		}
	}

图片

复制代码
PdfPCell cell = new PdfPCell();
// 我这里是根据文件服务器上的图片链接进行获取的。
cell.setImage(Image.getInstance(MinioUtil.getUrlName(imageUrl)));

实际图

相关推荐
SoFlu软件机器人6 分钟前
Java 框架配置自动化:告别冗长的 XML 与 YAML 文件
xml·java·自动化
贰拾wan19 分钟前
【Java-EE进阶】SpringBoot针对某个IP限流问题
java·spring boot·后端·idea
青云交30 分钟前
【金仓数据库征文】-- 金仓数据库:技术实践天花板级深度解析,手把手教你玩转企业级应用
java·性能调优·集群部署·金仓数据库 2025 征文·数据库平替用金仓·金仓数据库·语法兼容
AI视觉网奇32 分钟前
3d关键点 可视化
开发语言·python·pygame
向宇it42 分钟前
【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
开发语言·ui·unity·c#·编辑器·游戏引擎
Paran-ia42 分钟前
【2025版】Spring Boot面试题
java·spring boot·后端
LUCIAZZZ1 小时前
JVM之虚拟机运行
java·jvm·spring·操作系统·springboot
Python私教1 小时前
Rust:重新定义系统编程的安全与效率边界
开发语言·安全·rust
hello_ejb31 小时前
聊聊JetCache的缓存构建
java·前端·缓存
cainiao0806051 小时前
Java 大视界——Java 大数据在智慧交通智能停车诱导系统中的数据融合与实时更新
java·大数据·开发语言