PDFBox how to import acrofield from another pdf

2020-04-30 03:18发布

问题:

I have a problem with import exist acrofield from a pdf into another pdf. The two pdf are similar. I tried to import and save the file (code below). if I open it from the file system I do not see the changes, but if I open it with pdfbox I see the acrofiles inserted earlier. I notice that the file size has increased, but when I open it I do not see the fields fillable.

Thank you in advance

        PDDocument documentSrc = PDDocument.load(new File(SRC));
        PDAcroForm acroFormSrc = documentSrc.getDocumentCatalog().getAcroForm();

        PDDocument documentDest = PDDocument.load(new File(DEST));
        PDAcroForm acroFormDest = new PDAcroForm(documentDest);

        System.out.println("\n\n\n----------> FIELDS OF DOC SOURCE");
        for(PDField field : acroFormSrc.getFields()) {
            System.out.println(field);
        }

        acroFormDest.setCacheFields(true);
        acroFormDest.setFields(acroFormSrc.getFields());
        documentDest.getDocumentCatalog().setAcroForm(acroFormDest);

        documentDest.save(DEST_MERGED);
        documentDest.close();
        documentSrc.close();

        PDDocument documentMERGED = PDDocument.load(new File(DEST_MERGED));
        PDAcroForm acroFormMERGED = documentMERGED.getDocumentCatalog().getAcroForm();

        System.out.println("\n\n\n----------> FIELDS OF DOC MERGED");
        for(PDField field : acroFormMERGED.getFields()) {
            System.out.println(field);
        }

        documentMERGED.close();

回答1:

i solved this way:

    try
    {

        PDDocument documentSrc = PDDocument.load(new File(SRC));
        PDAcroForm acroFormSrc = documentSrc.getDocumentCatalog().getAcroForm();

        PDDocument documentDest = PDDocument.load(new File(DEST));
        PDAcroForm acroFormDest = new PDAcroForm(documentDest);

        acroFormDest.setCacheFields(true);
        acroFormDest.setFields(acroFormSrc.getFields());
        documentDest.getDocumentCatalog().setAcroForm(acroFormDest);

        int pageIndex = 0;
        for(PDPage page: documentSrc.getPages()){
            documentDest.getPage(pageIndex).setAnnotations(page.getAnnotations());
            documentDest.getPage(pageIndex).setResources(page.getResources());
            pageIndex++;
        }

        documentDest.save(DEST_MERGED);
        documentDest.close();
        documentSrc.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Thanks for your support :)