I'm using iText to merge several PDFs with layer. Each pdf file contains two layers: 'Cut' and 'Crease'.
Code:
public void testMergePdfMerger() throws Exception {
String[] srcPdfs = new String[]{
resourceFile("pdf/4901.pdf"),
resourceFile("pdf/4902.pdf"),
// more files here...
};
String destPdf = targetFile("MergerSimple.pdf");
try (PdfDocument tgt = new PdfDocument(new PdfWriter(destPdf))) {
PdfMerger merger = new PdfMerger(tgt);
for (String srcPdf : srcPdfs) {
try (PdfDocument src = new PdfDocument(new PdfReader(srcPdf))) {
merger.merge(src, 1, src.getNumberOfPages());
}
}
}
}
The target pdf contains the correct content. However, the layer list contains many layers with similar names.
Can I change some code so that the merged file only contains two layers: 'Cut' and 'Crease' ?
With the following code, I can remove the layer name postfix.
List<PdfLayer> layers = tgt.getCatalog().getOCProperties(false).getLayers();
for(PdfLayer layer: layers) {
String currentLayerName = layer.getPdfObject().get(PdfName.Name).toString();
layer.setName(currentLayerName.replaceAll("_\d+$", ""));
}
But still not clear how to reuse the layer name from the first input pdf file.
question from:
https://stackoverflow.com/questions/65843242/how-to-merge-multiple-pdfs-with-same-layer-names-and-get-a-shorter-layer-list-fo 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…