iText 5

news/2024/5/17 11:45:29

依赖

    implementation 'com.itextpdf:itextpdf:5.5.13.3'implementation 'com.itextpdf:itext-asian:5.2.0'implementation 'com.alibaba:fastjson:1.2.83'compileOnly 'org.projectlombok:lombok:1.18.22'annotationProcessor "org.projectlombok:lombok:1.18.22"

测试

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;public class GeneratePdfReport {private static final Logger logger = LoggerFactory.getLogger(GeneratePdfReport.class);public static void main(String[] args) {FontFactory.registerDirectories();// drawTable();drawRowspan0();}public static ByteArrayInputStream citiesReport(List<City> cities) {Document document = new Document();ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();try {// 建立一个书写器(内存流方式)PdfWriter.getInstance(document, byteArrayOutputStream);document.open();PdfPTable table = new PdfPTable(3);table.setWidthPercentage(60);table.setWidths(new int[]{1, 3, 3});Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD);PdfPCell h_cell;h_cell = new PdfPCell(new Phrase("Id", headFont));h_cell.setHorizontalAlignment(Element.ALIGN_CENTER);// LeadingParagraph paragraph = new Paragraph();paragraph.setLeading(2.5f);table.addCell(h_cell);h_cell = new PdfPCell(new Phrase("Name", headFont));h_cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(h_cell);h_cell = new PdfPCell(new Phrase("Population", headFont));h_cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(h_cell);for (City city : cities) {PdfPCell cell;cell = new PdfPCell(new Phrase(city.getId().toString()));cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase(city.getName()));cell.setPaddingLeft(5);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_LEFT);table.addCell(cell);cell = new PdfPCell(new Phrase(String.valueOf(city.getPopulation())));cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_RIGHT);cell.setPaddingRight(5);table.addCell(cell);}document.add(table);} catch (DocumentException ex) {logger.error("Error occurred: {0}", ex);} finally {document.close();}return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());}@SneakyThrowsprivate static void drawTable() {String[] headers = {"列一", "列二", "列三", "列四", "列五", "列六"};String list = "[{\"balance\":\"42402\",\"changeDate\":\"20211026111641\",\"dgst\":\"SSTR\",\"outMoney\":\"0\",\"bankSeqNo\":\"00000000000641199893\",\"inMoney\":\"11539\"},{\"balance\":\"30863\",\"changeDate\":\"20211005133736\",\"dgst\":\"SALE\",\"outMoney\":\"7500\",\"bankSeqNo\":\"00000000000635138192\",\"inMoney\":\"0\"},{\"balance\":\"38363\",\"changeDate\":\"20210926113940\",\"dgst\":\"SSTR\",\"outMoney\":\"0\",\"bankSeqNo\":\"00000000000632420138\",\"inMoney\":\"11539\"},{\"balance\":\"26824\",\"changeDate\":\"20210925111144\",\"dgst\":\"SALE\",\"outMoney\":\"11150\",\"bankSeqNo\":\"00000000000632752221\",\"inMoney\":\"0\"},{\"balance\":\"37974\",\"changeDate\":\"20210922083109\",\"dgst\":\"SALE\",\"outMoney\":\"4860\",\"bankSeqNo\":\"00000000000631851353\",\"inMoney\":\"0\"},{\"balance\":\"42834\",\"changeDate\":\"20210919153251\",\"dgst\":\"SALE\",\"outMoney\":\"7910\",\"bankSeqNo\":\"00000000000631503750\",\"inMoney\":\"0\"},{\"balance\":\"50744\",\"changeDate\":\"20210917080014\",\"dgst\":\"SALE\",\"outMoney\":\"5870\",\"bankSeqNo\":\"00000000000630377865\",\"inMoney\":\"0\"},{\"balance\":\"56614\",\"changeDate\":\"20210915153430\",\"dgst\":\"SALE\",\"outMoney\":\"8560\",\"bankSeqNo\":\"00000000000630120441\",\"inMoney\":\"0\"},{\"balance\":\"65174\",\"changeDate\":\"20210830103432\",\"dgst\":\"SALE\",\"outMoney\":\"6200\",\"bankSeqNo\":\"00000000000625635279\",\"inMoney\":\"0\"},{\"balance\":\"71374\",\"changeDate\":\"20210825124135\",\"dgst\":\"SSTR\",\"outMoney\":\"0\",\"bankSeqNo\":\"00000000000624479550\",\"inMoney\":\"11539\"}]";List<Map<String, Object>> mapList = (List) JSON.parseArray(list);ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();PdfWriter writer = null;Document document = null;try {// 创建纵向文件{// 生成pdfdocument = new Document();// 页面大小Rectangle rectangle;{rectangle = new Rectangle(PageSize.A4);// 页面背景颜色rectangle.setBackgroundColor(BaseColor.WHITE);}document.setPageSize(rectangle);// 页边距 左,右,上,下document.setMargins(20, 40, 40, 20);}// 建立一个书写器(内存流方式)PdfWriter.getInstance(document, byteArrayOutputStream);// 打开文件document.open();// 添加字体样式Font bigFont, blueFont;{BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);bigFont = new Font(bf, 14, Font.NORMAL, BaseColor.BLACK);blueFont = new Font(bf, 10, Font.NORMAL, BaseColor.BLACK);}// 段落内容Paragraph title;{title = new Paragraph("测试pdf", bigFont);title.setSpacingBefore(5);title.setSpacingAfter(5);// 文字居中显示title.setAlignment(Element.ALIGN_CENTER);}// 添加段落内容document.add(title);// 创建表格列数PdfPTable table;{table = new PdfPTable(headers.length);// 宽度100%填充table.setWidthPercentage(100);}// 创建表头{for (String header_text : headers) {PdfPCell cell;{cell = new PdfPCell(new Paragraph(header_text, bigFont));cell.setFixedHeight(27f);// 默认不跨行、跨列cell.setRowspan(1);cell.setColspan(1);// 居中显示cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 设置边框cell.setBorder(Rectangle.RIGHT + Rectangle.BOTTOM);cell.setPadding(5);}table.addCell(cell);}}// document.add(table); // mark// 填充数据for (Map<String, Object> map : mapList) {// 获取对象// Map 获取key & valuefor (Map.Entry<String, Object> entry : map.entrySet()) {Object value = entry.getValue();PdfPCell cell;{cell = new PdfPCell(new Paragraph(value.toString(), blueFont));cell.setFixedHeight(27f);// 默认不跨行、跨列 ps: 0 or 1 没有区别cell.setRowspan(1);cell.setColspan(1);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_LEFT);// 设置边框cell.setBorder(Rectangle.LEFT);// cell.setBorderWidthRight(1f);cell.setPadding(5);}table.addCell(cell);}// document.add(table); // mark}document.add(table); // mark} catch (DocumentException | IOException ignored) {} finally {if (document != null) {// 关闭文档document.close();}if (writer != null) {// 关闭书写器writer.close();}}Base64.Encoder encoder = Base64.getEncoder();String url = "data:application/pdf;base64," + encoder.encodeToString(byteArrayOutputStream.toByteArray());System.out.println(url);}@SneakyThrowspublic static void drawRowspan0() {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();Document document = new Document();PdfWriter.getInstance(document, byteArrayOutputStream);document.open();PdfPTable table = new PdfPTable(3); // 创建一个三列的表格for (int i = 0; i < 5; i++) {PdfPCell cell = new PdfPCell();cell.addElement(new com.itextpdf.text.Paragraph("Cell 1"));if (i == 2)cell.setRowspan(2); // 第三个单元格不跨行// else//     cell.setRowspan(2);table.addCell(cell);}document.add(table);document.close();Base64.Encoder encoder = Base64.getEncoder();String url = "data:application/pdf;base64," + encoder.encodeToString(byteArrayOutputStream.toByteArray());System.out.println(url);}}
  • 添加图层

添加图层

// 引入itextpdf库X
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;// 打开PDF文件
PdfReader reader = new PdfReader("input.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));// 创建图层对象
PdfLayer layer = new PdfLayer("New Layer", stamper.getWriter());// 添加内容到图层
layer.setOn(true);// 将图层添加到PDF文件
stamper.addAnnotation(layer);
stamper.close();
// 引入itextpdf库X
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;// 打开PDF文件
PdfReader reader = new PdfReader("input.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));// 创建图层对象
PdfLayer layer = new PdfLayer("New Layer", stamper.getWriter());// 添加内容到图层
layer.setOn(true);// 将图层添加到PDF文件
stamper.addAnnotation(layer);
stamper.close();

(以下内容忽略)

jdk 运行 js

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;class JavascriptUtils {public static void runDisplay() {ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");try {// REPL read eval print loopengine.eval(new FileReader("test.js"));Invocable invocable = (Invocable) engine;Object result;result = invocable.invokeFunction("addNumber", 1, 2);System.out.println(engine);System.out.println(result);System.out.println(result.getClass());} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {e.printStackTrace();}}public static void main(String[] args) {runDisplay();}
}
  • 事件监听
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class EventDemo {@Beanpublic MyListener myListener() {// 使用注入进行注册{监听器} 来响应其他{自定义事件}return new MyListener();}public static void main(String[] args) {// 在 Spring 中,事件发布和监听器注册都是通过 ApplicationContext 来实现的AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(EventDemo.class);context.publishEvent(new MyEvent("hello world"));// Spring 内置了很多事件,例如:ContextStartedEvent,ContextStoppedEvent,// ContextRefreshedEvent,ContextClosedEvent (应用程序的不同生命周期阶段)// RequestHandledEvent (Web 请求处理过程) 等}private static class MyEvent extends ApplicationEvent {private final String message;public MyEvent(String message) {super(message);this.message = message;}public String getMessage() {return message;}}// (need inject)private static class MyListener implements ApplicationListener<MyEvent> {@Overridepublic void onApplicationEvent(MyEvent event) {System.out.println("Received event: " + event.getMessage());}}
}

http://www.mrgr.cn/p/11458804

相关文章

[转]AspNetCore容器化(Docker)部署(三) —— Docker Compose容器编排

一.前言 上一篇部署了一个最基础的helloworld应用,创建了两个容器和一个network,还算应付得过来。 如果该应用继续引入mysql、redis、job等若干服务,到时候发布一次得工作量之大就可想而知了,这时候就需要用到Docker Compose。 Docker Compose是一个用于定义和运行多容器Do…

使用rollup打包一个npm包

使用rollup打包一个npm包 前言:在这个都在使用 npm install,来安装包的时代,你是否想发布一个自己的npm包,或者你工作中是否要发布一个npm包,来到你的项目中到处使用呢?(不晓得npm是什么的请移步:npm) 那么今天我们就来学习一下怎样打包一个自己的npm包 1.首先准备环境 …

LevelDB源码阅读笔记(1、整体架构)

LevelDB源码阅读笔记&#xff08;1、整体架构&#xff09; LeveDB源码笔记系列&#xff1a; LevelDB源码阅读笔记&#xff08;0、下载编译leveldb&#xff09; LevelDB源码阅读笔记&#xff08;1、整体架构&#xff09; 前言 对LevelDB源码的博客&#xff0c;我准备采用总…

ROS2笔记4--服务通讯

ROS2中话题通讯可以实现多个ROS节点之间数据的单向传输,不过话题通讯是一种异步通信机制,发布者无法准确知道订阅者是否收到消息。而服务通信是一种基于请求响应的通信模型,在通信双方中客户端发送请求数据到服务端,服务端响应结果给客户端。 从服务实现机制看这种形式是C…

从系统设计到撸代码?我用了这些方法和工具

大家在撸代码之前会进行业务系统流程设计么?你们在设计的时候又用到了哪些工具呢?大家好,我是老猫。今天和大家分享一下程序员日常的绘图思路,以及一些老猫日常使用的绘图工具。 为什么要画图? 我们在进行系统设计的时候,为了更加具象地呈现系统的轮廓以及各个组件或者系…

element-plus 实现 table 列动态显示,宽度调整,顺序调整

效果图实现原理定义一个数组,保存列的属性, 标题,是否显示,宽度等 v-for 循环,动态设置列 弹出界面来修改这个数组,就实现了.

Linux上的uname

2024年4月19日&#xff0c;周五上午 uname 是一个常用的命令行工具&#xff0c;uname 的全称是 “Unix Name”&#xff0c;它是一个 Unix 和类 Unix 操作系统上的命令行工具&#xff0c;用于获取操作系统相关的信息&#xff0c;如内核版本、系统架构、主机名等。 它通常用于查…

GreatSQL 死锁案例分析

1.背景概述 客户业务发生死锁的报错,根据业务程序日志及业务流程,发现造成死锁的原因是:事务1 delete + insert ,事务2 delete + insert 2个事务交替执行导致的死锁;由于GAP锁阻塞了插入意向锁,并且当delete的数据存在时死锁不会发生,当delete的数据不存在时,会发生死…

如何基于香橙派AIpro对视频/图像数据进行预处理

昇腾CANN提供了两种专门用于数据预处理的方式:AIPP和DVPP。本文分享自华为云社区《如何基于香橙派AIpro对视频/图像数据进行预处理》,作者: 昇腾CANN。 受网络结构和训练方式等因素的影响,绝大多数神经网络模型对输入数据都有格式上的限制。在计算机视觉领域,这个限制大多…

yolov7模型输出层预测方法解读

本文从代码的角度分析模型训练阶段输出层的预测包括以下几个方面&#xff1a; 标注数据&#xff08;下文统称targets&#xff09;的正样本分配策略&#xff0c;代码实现位于find_3_positive。候选框的生成&#xff0c;会介绍输出层的预测值、GT、grid、 anchor之间的联系损失函…

ROS笔记[2]-获取OpenMV数据并发布到ROS消息

Orangepi(香橙派)通过USB-CDC获取OpenMV数据并使用Python发布到ROS的/openmv主题,实现打印"hello ros"字符串.摘要 Orangepi(香橙派)通过USB-CDC获取OpenMV数据并使用Python发布到ROS的/openmv主题,实现打印"hello ros"字符串. 关键信息python3.8 ROS1:Noe…

vue引入字体icon

这里我用的是阿里图标库 1.2.3.4.在vue的assets文件中增加一个font文件把解压后的文件复制进去,并在mian.js中引入iconfont.css5.1.使用,复制以下代码在页面中使用 <h1>欢迎 <i class="iconfont">&#xe67c;</i></h1> 5.1.2使用,复制一…

万象奥科邀您参加RK3568+AMP混合部署线下实操活动-北京站

4月25日,万象奥科将携手RT-Thread在北京举办线下workshop,带您体验RK3568+OpenAMP实现RT-Thread与Linux同时运行的开发方式,实现在电力、机器人、工业控制、工业互联网、新能源等领域的高效应用。4月25日,万象奥科将携手RT-Thread在北京举办线下workshop,带您体验RK3568+O…

副本和就删码

分类 按照存储的结构存储可以分为集中式存储和分布式存储集中式存储 传统集中式存储采用控制器+硬盘柜的方式,通过冗余的双控制器提供数据管理和读写能力(也有超过2个控制器的多控存储,多见于高端存储),通过控制器自带的硬盘槽位或扩展硬盘柜提供存储空间,如下图。集中式…

多因子模型的因子分组-聚类分析

优质博文&#xff1a;IT-BLOG-CN 之前我们已经介绍了简单、高效的克隆巴赫α系数和科学有效的主成分分析对因子进行分组&#xff0c;我们将继续介绍一种复杂的方法----聚类分析&#xff08;Cluster Analysis&#xff09;。 聚类分析根据多个因子某一方面的相似性进行归类&…

JMeter下载与环境配置

前置 使用JMeter前需要先配置好Java的环境变量,不会的朋友可以阅读:https://www.cnblogs.com/test-gang/p/18144441 JMeter下载 JMeter官网:https://jmeter.apache.org/ 进入官网后,点击左边Download Releases进入Download Releases,页面会展示两种版本Source 是源代码版,…

DbMigrator迁移数据库报错:The ConnectionString property has not been initialized.

问题 执行.DbMigrator时报错:The ConnectionString property has not been initialized.原因 情况一 DbContext中没有指定连接字符串 解决方案情况二 appsettings.json 配置文件的属性没有设置为始终复制 解决方案 右键appsettings.json选择属性>复制到输出目录选择始终复制…

矩阵求导(一)

前言 在大学的微积分课程中,我们学习过关于标量函数的导数。但是当我们求解一个多元函数的极值时,单独一个自变量的偏导数往往不能告诉我们太多信息,于是我们有一种天然的想法是要把每个自变量的偏导数放在一起,看看他们的联合效果如何。这个过程其实是一个向量求导的过程。…

HTTP/HTTPS详解

HTTP/HTTPS详解 1. HTTP1.1 HTTP基础知识1.2 HTTP建立和断开连接 2. HTTPS 1. HTTP 1.1 HTTP基础知识 HTTP是互联网上应用最为广泛的一种网络协议&#xff0c;是一个客户端和服务器端请求和应答的标准&#xff08;TCP&#xff09;&#xff0c;用 于从WWW服务器传输超文本到本…

他来了他来了,.net开源智能家居之苹果HomeKit的c#原生sdk【Homekit.Net】1.0.0发布,快来打造你的私人智能家居吧

背景介绍 hi 大家好,我是三合,作为一个非著名懒人,每天上完班回到家,瘫在沙发上一动都不想动,去开个灯我都嫌累,此时,智能家居拯救了我,只需要在手机点点点,开关灯,空调,窗帘就都搞定了,一开始我用的是开源的home assistan,俗称HA,搭配上hass-xiaomi-miot以及hap…