'Iterative cloning of a Page with PDFBox and writing each of them differently

I want to iterate over a list of input data. For every input (which also has input objects to write on a template) I want to clone the template and write said input.

Some how the pages I have cloned are written overlaid with every input given in the whole list.

I tried to deepcopy the COSDictonary or generate the COSDictonary for every iteration seperatly.

 PDDocument templateDocument = PDDocument.load(new File(path));
    templateDocument.setAllSecurityToBeRemoved(true);
    PDDocument finalDocument = new PDDocument();

    if (templateDocument != null) {
        PDFCloneUtility cloner = new PDFCloneUtility(templateDocument);
        PDPage originalPage = templateDocument.getPage(0);
        int count=0;
        //inputs is an ArrayList of Arraylists
        for (List<Input> input : inputs) {
            //fieldEnrichment() maps the input data with the loaded fields from a config file
            fieldEnrichment(fields, input);
            COSDictionary pageDictionary = (COSDictionary) cloner.cloneForNewDocument(originalPage)
            PDPage page = new PDPage(pageDictionary);
            finalDocument.addPage(page);
            //writeFieldsIntoLastPage() creates a contentStream and writes the input into the page
            writeFieldsIntoLastPage(finalDocument, fields);
            clearFieldsFromInput(fields);
            count++;
        }

        finalDocument.save(new File("result/data/" + "Test_" + splitPathToName(path)));
        finalDocument.close();

    }

}

What is the correct way to deep clone PDPage? his solution solved the problem by creating a new pdf file for every page, but since wanting to generate +10000 pages a Memory issue occurs.

Has somebody an idea how to use the templatePage of the originalDoc "unwritten" for every loop adding it directly into the finalDocument?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source