Home > OS >  Unable to open pdf after creation
Unable to open pdf after creation

Time:10-29

I'm writing a program that takes a template PDF with a bunch of blank form fields, makes a copy of it, fills in the forms, then flattens the fields.

One of these templates has a ton of fields so writing a method that fills in all the fields results in an error that says code is too large due to the size limits on methods.

To work around this, I closed the destination file then tried to open it in another method where I could continue to fill in the fields, but this results in an error that says "(The requested operation cannot be performed on a file with a user-mapped section open)"

I ended the first method by closing the PDF, so I'm not sure what the issue is. The program will execute the first method, fill the fields but throws the error when it get to the 2nd method. Sample code below.

public void E2fill(String srcE2, String destE2) throws IOException
{
    try
    {
        PdfDocument pdf2 = new PdfDocument(new PdfReader(destE2), new PdfWriter(dest2E2));
        PdfAcroForm form2 = PdfAcroForm.getAcroForm(pdf2, true);
        Map<String, PdfFormField> fields2 = form2.getFormFields();
        PdfFormField field2;
        fields2.get("fieldname1").setValue(stringname1);
        //lots more field fills
        pdf2.close()
    }
    catch(Exception x)
    {
        System.out.println(x.getMessage());
    }
}

public void E2fill2(String destE2, String dest2E2) throws IOException
{
    try
    {
        PdfDocument pdf2 = new PdfDocument(new PdfReader(destE2), new PdfWriter(dest2E2));
        PdfAcroForm form2 = PdfAcroForm.getAcroForm(pdf2, true);
        Map<String, PdfFormField> fields2 = form2.getFormFields();
        PdfFormField field2;
        fields2.get("fieldname546").setValue(stringname546);
        //more field fills
        form2.flattenFields();
        pdf2.close();
    }
    catch(Exception x)
    {
        System.out.println(x.getMessage());
    }
}

CodePudding user response:

I suggest you try this:

    public void fill(String srcE2, String destE2) {
        PdfDocument pdf2 = new PdfDocument(new PdfReader(destE2), new PdfWriter(dest2E2));
        PdfAcroForm form2 = PdfAcroForm.getAcroForm(pdf2, true);
        Map<String, PdfFormField> fields2 = form2.getFormFields();
        E2fill(fields2);
        E2fill2(fields2);
        form2.flattenFields();
        pdf2.close();
    }

    public void E2fill(Map<String, PdfFormField> fields2) throws IOException 
    {
        fields2.get("fieldname1").setValue(stringname1);
        //lots more field fills
    }

    public void E2fill2(PdfAcroForm form2) throws IOException {
        fields2.get("fieldname546").setValue(stringname546);
        //more field fills
    }
  • Related