0
try{
    PDDocument doc = PDDocument.load( file );

    PDPage page = doc.getPages().get( 1 );

    COSDictionary pageDict = page.getCOSObject();

    int pagesToBeAdded = pagesToBeAdded(merchandiseLineItemsCount);

    for(int i=0;i<pagesToBeAdded;i++){
        COSDictionary newPageDict = new COSDictionary(pageDict);
        //newPageDict.removeItem(COSName.ANNOTS);
        PDPage newPage = new PDPage(newPageDict);
        doc.addPage(newPage);
    }

    return doc;
}

So this is how I am adding the page to a template doc .. and I am facing a problem that I can't get the PDfields for the newly added page when I iterate over that page for setting the value of those PDFields. I am also changing the text of the page added by checking the "TJ" operator and setting the value of COSString

mkl
  • 90,588
  • 15
  • 125
  • 265
  • 1
    Beware, you appear to be subject to a misconception. A PDF document contains only a single form the fields of which may have visualizations spread over all the pages. Thus, by simply adding copies of the same page to a target document, you don't generate more fields, you merely generate more visualizations of the constant set of fields. Furthermore your code generates invalid PDFs, *a given annotation dictionary shall be referenced from the **Annots** array of only one page,* but all your flat copies of the source page refer to the identical annotation dictionaries. – mkl Dec 06 '19 at 12:10
  • 1
    Instead of your shallow copies, you should use the PDFBox `PDFMergerUtility` employing `setAcroFormMergeMode` accordingly. – mkl Dec 06 '19 at 12:16
  • @mkl so how are we supposed to generate new fields for a new page with some edited visualisations ..? – Dibyansh Yadav Dec 08 '19 at 14:44
  • https://stackoverflow.com/questions/29371129/java-pdfbox-fill-out-pdf-form-append-it-to-pddocument-and-repeat will this be helpful in my case?.. I just want some similar fields from a page on another page. I wonder how it will accurately position those fields on that specific page with no fields. – Dibyansh Yadav Dec 08 '19 at 18:35
  • If you want to use the template to put these fields "over" the existing page, then yes that answer would be helpful. The positions come from the positions (getRect) in the widget annotations. I don't know what you mean with "some edited visualisations". – Tilman Hausherr Dec 09 '19 at 09:34
  • @DibyanshYadav *"will this be helpful in my case?"* - To me it looks like it might be a base for a solution of your problem. It assumes only a single field `SampleField` in the template but it should be obvious how to generalize this. It would be cleaner, though, to use `PDFMergerUtility.appendDocument(finalDoc, doc)` instead of `finalDoc.addPage(pages.get(0))`. – mkl Dec 09 '19 at 10:20

0 Answers0