java图层添加图片_java PDF添加图层的方法 支持多页图层添加

本文介绍如何使用Java的iText库将图片作为图层添加到PDF中,支持多页添加。通过示例代码展示了一个方法,将图片按照指定页数顺序合成为PDF的新页面。
摘要由CSDN通过智能技术生成

java PDF添加图层,支持多页图层添加,具体如下

代码:

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.List;

import com.itextpdf.text.DocumentException;

import com.itextpdf.text.Image;

import com.itextpdf.text.pdf.PdfContentByte;

import com.itextpdf.text.pdf.PdfReader;

import com.itextpdf.text.pdf.PdfStamper;

public class PdfUtils {

/**

* PDF添加图层

*

* @param srcPdf

* 原PDF文件路径

* @param distPdf

* 合成PDF输出路径

* @param layerPathArr

* 图层路径列表,图层名称需为数字(按照图片名称数字顺序合成在PDF对应页数上)

* @return

* @throws IOException

* @throws DocumentException

*/

public static String markLocalImage42Dist(String srcPdf, String distPdf, List layerPathArr)

throws IOException, DocumentException {

File srcPdfFile = new File(srcPdf);

if (!srcPdfFile.exists()) {

throw new IllegalArgumentException("找不到需要添加图层的pdf文件");

}

PdfReader reader = new PdfReader(srcPdf);

int n = reader.getNumberOfPages(); // PDF页数

PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(distPdf));

PdfContentByte over;

for (String layerPath : layerPathArr) {

File layerFile = new File(layerPath);

String currentPageNo = layerFile.getName().substring(0, layerFile.getName().lastIndexOf(".")); // 图片名称(对应页数)

boolean isNum = currentPageNo.matches("[0-9]+");

if (!isNum) {

throw new IllegalArgumentException("图层名称是不是数字");

}

Image img = Image.getInstance(layerPath);

img.setAbsolutePosition(0, 0);

if (n > 0 && n >= Integer.parseInt(currentPageNo)) {

over = stamp.getOverContent(Integer.parseInt(currentPageNo));

over.addImage(img);

}

}

stamp.close();

reader.close();

return distPdf;

}

}

测试:

public static void main(String[] args) throws IOException, DocumentException {

List imgUrlList = new ArrayList<>();

imgUrlList.add("D:/ts/testPDF/1.png");

//imgUrlList.add("D:/ts/testPDF/2.png");

imgUrlList.add("D:/ts/testPDF/3.png");

markLocalImage42Dist("D:/ts/testPDF/testPDF.pdf", "D:/ts/testPDF/testPDF2.pdf", imgUrlList);

}

结果:

f99577111d683dbb415ed4f46acf2d05.png

d5c5b4cfe87af5a2d4ee4eec66da090a.png

原PDF:

6dd0dfb2e997c591d26686da0c13864f.png

69f890dacc921983ea59677cd9106442.png

f8972021a5ad61f21a4055b16e1bdff7.png

合成后PDF:

9b090fcbafacd25ab3d5e5fabc09b925.png

75d1ae7414ccaaf300f8d026f64e3b10.png

77929f7139c3431f6f9c4c93c964efa9.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值