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

相关推荐
学长毕设2 小时前
基于SpringBoot的建筑材料管理系统-附源码
java·spring boot·后端
摸爬滚打的小李2 小时前
关于 Arthas
java·后端
砚底藏山河3 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融
yuniko-n3 小时前
【JUC】原子类
java
惊讶的猫3 小时前
Query 改写
java·rag
信誓旦旦的程序猿3 小时前
【Python量化实战宝典 #18】MACD 金叉死叉手册:DIF、DEA、柱体全拆解(Python 可跑)
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
Misnearch3 小时前
第7章 面向对象技术
java·开发语言·软考
weixin_BYSJ19874 小时前
电竞先锋网站---附源码02032
java·vue.js·spring boot·python·django·tomcat·php
会编程的吕洞宾4 小时前
LangChain4j 流式输出实战:让 AI 回复像打字机一样逐字显示
java·开发语言·人工智能·后端
只是学习学习4 小时前
Java将文件转二维码导出MP4
java