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

相关推荐
Java后端的Ai之路19 分钟前
01、Python - 设计模式介绍
java·人工智能·python·设计模式·通用
zzzll111120 分钟前
大模型技术原理与应用实践
java·数据库·人工智能
asdfg125896325 分钟前
java.util包中的ArrayList&&Collections的目的和用途
java·arraylist·collections
余额瞒着我当琳26 分钟前
C++STL--list底层实现,迭代器分类,模拟list的迭代器封装、实现
java·开发语言·c++
吴声子夜歌32 分钟前
Java面试——数据结构(二)
java·数据结构·面试
栀栀栀栀栀栀36 分钟前
2026/8/23 maven springboot
java·spring boot·maven
SeaDhdhdhdhdh9 小时前
MCP Server 搭建与使用指南
java·ai·agent·mcp
YH55269849 小时前
GPT‑5.6 Sol 原本支持 1M 上下文,Codex 现已放开此前限制,如何看待这次调整?
java·jvm·人工智能·gpt·算法·chatgpt
AI_小站10 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
许彰午10 小时前
03-三种开发模式
java·架构