欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-08-26 08:11:46|栏目:JAVA代码|点击:

 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:

上一篇:java配置变量的解释,搬运他人优质评论(推荐)

栏    目:JAVA代码

下一篇:java多线程处理执行solr创建索引示例

本文标题:java PDF添加图层的方法 支持多页图层添加

本文地址:http://www.codeinn.net/misctech/169927.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有