Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

java - How to merge multiple PDFs with same layer names and get a shorter layer list for the output

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.

Merged PDF file layers

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+$", ""));
        }

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))) {
    [...]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...