Java PDF adds layers, supports multi-page layer addition, as follows
Code:
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.List;import com.ithtpdf.text.DocumentException;import com.ithtpdf.text.Image;import com.ithtpdf.text.pdf.PdfContentByte;import com.ithtpdf.text.pdf.PdfReader;import com.ithtpdf.text.pdf.PdfStamper;public class PdfUtils { /** * PDFAdd layer* * @param srcPdf * Original PDF file path * @param distPdf * Synthesize PDF output path * @param layerPathArr * Layer path list, the layer name must be number (combined on the number of pages corresponding to PDF in the order of image names and numbers) * @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("The pdf file that needs to be added to the layer cannot be found"); } PdfReader reader = new PdfReader(srcPdf); int n = reader.getNumberOfPages(); // Number of PDF pages 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(".")); // Image name (corresponding to the number of pages) boolean isNum = currentPageNo.matches("[0-9]+"); if (!isNum) { throw new IllegalArgumentException("Is the layer name a number"); } 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; }}test:
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); }result:
Original PDF:
After synthesis PDF:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.