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

相关推荐
小江的记录本11 小时前
【Spring全家桶】Spring Cloud 2023.0.x:微服务核心理论、CAP/BASE定理(附《思维导图》+《面试高频考点清单》)
java·spring boot·后端·spring·spring cloud·微服务·面试
Solis程序员11 小时前
缓存三剑客预防策略
java·spring·缓存
我登哥MVP11 小时前
Spring Boot 从“会用”到“精通”:Model-Map原理
java·spring boot·后端·spring·servlet·maven·mybatis
程序猿乐锅11 小时前
【苍穹外卖|Day02】后台接口自测闭环:Token、DTO 与 yml 配置
java·开发语言
心之伊始11 小时前
Spring Boot Actuator + Micrometer 自定义业务指标:不只是健康检查
java·架构·源码分析·csdn
Eason_LYC11 小时前
【GetShell 实战】CVE-2026-34486 Tomcat 加密拦截器绕过:从漏洞验证到反弹 Shell 全流程
java·渗透测试·tomcat·java反序列化·rce·远程代码执行漏洞·cve-2026-34486
qq_25183645711 小时前
基于java 税务管理系统设计与实现
java·开发语言
超梦dasgg11 小时前
Java 生产环境分布式定时任务全解(实战落地版)
java·开发语言·分布式
破土士V11 小时前
Java基础知识集合
java·开发语言