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:

以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。