Reputation: 660
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.
Upvotes: 0
Views: 444
Reputation: 512
You can set the smart mode
on the PdfWriter
to enable the reuse of resources (see https://api.itextpdf.com/iText7/java/7.1.14/com/itextpdf/kernel/pdf/PdfWriter.html#setSmartMode-boolean-)
try (PdfDocument tgt = new PdfDocument(new PdfWriter(destPdf).setSmartMode(true))) {
[...]
}
Upvotes: 2