Is it possible to modify PDF Form Field Names?

前端 未结 9 2177
一个人的身影
一个人的身影 2021-02-06 06:05

Here\'s the situation. I have a PDF with automatically generated pdf form field names. The problem is that these names are not very user friendly. They look something like :

9条回答
  •  情话喂你
    2021-02-06 06:25

    Here is a java example found in the book, "iText in Action"

    This is taken from their example source code for the book and helped me immensely with this same issue. part2.chapter06.ConcatenateForms2

    public static void main(String[] args)
        throws IOException, DocumentException {
        // Create a PdfCopyFields object
        PdfCopyFields copy
            = new PdfCopyFields(new FileOutputStream(RESULT));
        // add a document
        PdfReader reader1 = new PdfReader(renameFieldsIn(DATASHEET, 1));
        copy.addDocument(reader1);
        // add a document
        PdfReader reader2 = new PdfReader(renameFieldsIn(DATASHEET, 2));
        copy.addDocument(reader2);
        // Close the PdfCopyFields object
        copy.close();
        reader1.close();
        reader2.close();
    }
    
    
    private static byte[] renameFieldsIn(String datasheet, int i)
        throws IOException, DocumentException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Create the stamper
        PdfStamper stamper = new PdfStamper(new PdfReader(datasheet), baos);
        // Get the fields
        AcroFields form = stamper.getAcroFields();
        // Loop over the fields
        Set keys = new HashSet(form.getFields().keySet());
        for (String key : keys) {
            // rename the fields
            form.renameField(key, String.format("%s_%d", key, i));
        }
        // close the stamper
        stamper.close();
        return baos.toByteArray();
    }
    

提交回复
热议问题