java PDF添加图层的方法 支持多页图层添加
更新时间:2018年02月01日 09:58:50 作者:漂流的老妖怪
这篇文章主要为大家详细介绍了java PDF添加图层的方法,支持多页图层添加,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
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<String> 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<String> 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); }
结果:
原PDF:
合成后PDF:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
IDEA 2020.1 for Mac 下载安装配置及出现的问题小结
这篇文章主要介绍了IDEA 2020.1 for Mac 下载安装配置及出现的问题小结,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-03-03Spring注解驱动之ApplicationListener异步处理事件说明
这篇文章主要介绍了Spring注解驱动之ApplicationListener异步处理事件说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-09-09关于Spring BeanPostProcessor的执行顺序
这篇文章主要介绍了Spring BeanPostProcessor的执行顺序,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-10-10Spring boot事务无效报错:Transaction not enabled问题排查解决
在业务代码中经常需要保证事务的原子性,但是有的时候确实是出现事务没有生效,这篇文章主要给大家介绍了关于Spring boot事务无效报错:Transaction not enabled问题排查的相关资料,需要的朋友可以参考下2023-11-11
最新评论