admin管理员组文章数量:1592311
工作上遇到一个小需求,需要在原有的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>
样例代码
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编辑pdf(itextpdf) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728139683a1147200.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论