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

相关推荐
zbguolei8 分钟前
Springboot上传文件与物理删除
java·spring boot·后端
jay神11 分钟前
基于SpringBoot的校园社团活动智能匹配与推荐系统
java·前端·spring boot·后端·毕业设计
可以吧可以吧11 分钟前
idea全家桶【常见报错处理】当出现 “We could not validate your license ... “ 提示时
java·ide·intellij-idea
装不满的克莱因瓶12 分钟前
IDEA rebuild project 到底有什么作用?
java·ide·intellij-idea
Java程序员威哥12 分钟前
Arthas+IDEA实战:Java线上问题排查完整流程(Spring Boot项目落地)
java·开发语言·spring boot·python·c#·intellij-idea
蒝莱茹茈23 分钟前
pdf-engine发布
pdf·pdfium
fl17683126 分钟前
基于python实现PDF批量加水印工具
开发语言·python·pdf
lqj_本人27 分钟前
Flutter PDF 渲染插件(pdf_image_renderer)适配鸿蒙 (HarmonyOS) 平台实战
flutter·pdf·harmonyos
Eugene__Chen39 分钟前
Java的SPI机制(曼波版)
java·开发语言·python
程序猿202343 分钟前
JVM与JAVA
java·jvm·python