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

后端 未结 11 2189
难免孤独
难免孤独 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:52

    After reading about pdf reference guide, I have discovered that you can quite easily set read-only mode for AcroForm fields by adding "Ff" key (Field flags) with value 1. This is what documentation stands about that:

    If set, the user may not change the value of the field. Any associated widget annotations will not interact with the user; that is, they will not respond to mouse clicks or change their appearance in response to mouse motions. This flag is useful for fields whose values are computed or imported from a database.

    so the code could look like that (using pdfbox lib):

     public static void makeAllWidgetsReadOnly(PDDocument pdDoc) throws IOException {
    
        PDDocumentCatalog catalog = pdDoc.getDocumentCatalog();
    
        PDAcroForm form = catalog.getAcroForm();
    
        List acroFormFields = form.getFields();
    
        System.out.println(String.format("found %d acroFrom fields", acroFormFields.size()));
    
        for(PDField field: acroFormFields) {
            makeAcroFieldReadOnly(field);
        }
    }
    
    private static void makeAcroFieldReadOnly(PDField field) {
    
        field.getDictionary().setInt("Ff",1);
    
    }
    

提交回复
热议问题