java编辑pdf(itextpdf)

工作上遇到一个小需求,需要在原有的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>

样例代码

java 复制代码
public class Test {

    public static void main(String[] args) {
        try {
            //读取源文件
            PdfReader pdfReader = new PdfReader("F:/pdf/before.pdf");
            //编辑后的文件
            PdfStamper stamper = new PdfStamper(pdfReader, new FileOutputStream("F:/pdf/after.pdf"));
            //获取第一页也的内容
            PdfContentByte pdfContentByte =stamper.getOverContent(1);
            //开始编辑
            pdfContentByte.beginText();
            //设置字体大小、样式
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            pdfContentByte.setFontAndSize(baseFont, 30);
            //要添加的内容的位置:x-距离左边的像素,y-距离底部的像素
            pdfContentByte.setTextMatrix(50, 300);
            //要添加的类容
            pdfContentByte.showText("我写了啥??????");
            pdfContentByte.endText();
            stamper.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

运行效果

before.pdf

after.pdf

相关推荐
shadowcz0077 分钟前
关于GEO的研究总结#使用 Notebooklm 来研究论文和整理报告#PDF分享
人工智能·pdf
whltaoin15 分钟前
【Java SE】Java IO体系深度剖析:从原理到实战的全方位讲解(包含流操作、序列化与 NIO 优化技巧)
java·开发语言·nio·se·io体系
Tony Bai7 小时前
Go 安全新提案:runtime/secret 能否终结密钥残留的噩梦?
java·开发语言·jvm·安全·golang
oioihoii7 小时前
C++11到C++23语法糖万字详解
java·c++·c++23
pengzhuofan7 小时前
Java演进与与工程师成长
java·开发语言
月明长歌7 小时前
再谈Java 继承与多态:从“能用”到“精通”,更深一层的原理与设计思维
java·开发语言
狗头实习生7 小时前
Spring常见的事务失效原因
java·数据库·spring
想个名字太难8 小时前
网络爬虫入门程序
java·爬虫·maven
diudiu_339 小时前
web漏洞--认证缺陷
java·前端·网络
heartbeat..9 小时前
注解 + 反射:Web 项目 Excel 一键导出工具 EnhancedExportExcelUtil 详解
java·excel·poi