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

相关推荐
草履虫建模3 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
qq_297574675 小时前
【实战教程】SpringBoot 实现多文件批量下载并打包为 ZIP 压缩包
java·spring boot·后端
老毛肚5 小时前
MyBatis插件原理及Spring集成
java·spring·mybatis
学嵌入式的小杨同学5 小时前
【Linux 封神之路】信号编程全解析:从信号基础到 MP3 播放器实战(含核心 API 与避坑指南)
java·linux·c语言·开发语言·vscode·vim·ux
lang201509285 小时前
JSR-340 :高性能Web开发新标准
java·前端·servlet
Re.不晚6 小时前
Java入门17——异常
java·开发语言
缘空如是6 小时前
基础工具包之JSON 工厂类
java·json·json切换
追逐梦想的张小年6 小时前
JUC编程04
java·idea
好家伙VCC6 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
南极星10057 小时前
蓝桥杯JAVA--启蒙之路(十)class版本 模块
java·开发语言