PDFBox: How to “flatten” a PDF-form?

后端 未结 11 2184
难免孤独
难免孤独 2020-12-09 06:32

How do I \"flatten\" a PDF-form (remove the form-field but keep the text of the field) with PDFBox?

Same question was answered here:

a quick

11条回答
  •  北海茫月
    2020-12-09 06:54

    Solution to flattening acroform AND retaining the form field values using pdfBox:

    • see solution at https://mail-archives.apache.org/mod_mbox/pdfbox-users/201604.mbox/%3C3BC7E352-9447-4458-AAC3-5A9B70B4CCAA@fileaffairs.de%3E

    The solution that worked for me with pdfbox 2.0.1:

    File myFile = new File("myFile.pdf");
    PDDocument pdDoc = PDDocument.load(myFile);
    PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog();
    PDAcroForm pdAcroForm = pdCatalog.getAcroForm();
    
    // set the NeedAppearances flag to false
    pdAcroForm.setNeedAppearances(false);
    
    
    field.setValue("new-value");
    
    pdAcroForm.flatten();
    pdDoc.save("myFlattenedFile.pdf");
    pdDoc.close();
    

    I didn't need to do the 2 extra steps in the above solution link:

    // correct the missing page link for the annotations
    // Add the missing resources to the form
    

    I created my pdf form in OpenOffice 4.1.1 and exported to pdf. The 2 items selected in the OpenOffice export dialogue were:

    1. selected "create Pdf Form"
    2. Submit format of "PDF" - I found this gave smaller pdf file size than selecting "FDF" but still operated as a pdf form.

    Using PdfBox I populated the form fields and created a flattened pdf file that removed the form fields but retained the form field values.

提交回复
热议问题