prule
prule

Reputation: 2584

PdfBox - Is it possible to programmatically invoke actions (javascript)

I have a PDF that has two fields with "Mouse Up" actions configured to run some javascript.

I've written code to fill in the PDF form fields, but haven't found a way to invoke the actions so far.

Is this something that is supported by PdfBox (or any other library) or will I have to just externalise this logic? (the PDF is owned and maintained by a 3rd party so duplicating the logic will not be a tidy solution).

Thanks.

[To Clarify]

The PDF has a form. The form contains a checkbox. The checkbox has an action defined - This action is configured to run javascript on Blur (or Mouse Up etc) which sets other form fields based on the status of the checkbox (checked/unchecked).

I can see the javascript code in the debugger if I do the following:

    // method 1
    {
        final InputStream src = this.getClass().getResourceAsStream("/spike/mydocument.pdf");

        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);

        {
            PdfFormField field = form.getField("field1");
            List<PdfWidgetAnnotation> widgets = field.getWidgets();

            for (PdfWidgetAnnotation widget : widgets) {
                log.info(widget.getAdditionalAction().get(PdfName.Bl));
            }

        }
    }

    // method 2
    {
        PDDocument doc = PDDocument.load(this.getClass().getResourceAsStream("/spike/mydocument.pdf"));
        PDAcroForm form = doc.getDocumentCatalog().getAcroForm();
        PDField field = form.getField("field1");
        List<PDAnnotationWidget> widgets = field.getWidgets();
        String js = ((COSString) widgets.get(0).getActions().getBl().getCOSObject().getDictionaryObject("JS")).getString();
        log.info(js);
    }

But as far as I can tell, I'm going to have to write some code to:

  1. Extract the javascript
  2. Execute the javascript from java, using the built in script engine, and passing in the pdf document form as a variable

I haven't found any support for this in PdfBox or iText so I assume I have to write it myself?

Upvotes: 1

Views: 1506

Answers (1)

1 :Better to read this: Using Javascript inside a PDF

2: With pdfbox, it is always possible to read (and write) the scripts:

And you could execute them outside, with the javascript engine of java (nashorn, JSR223, ...), but, as mkl said, the language is not enough: you must have the environment.

3: it should be very difficult to obtain the same behaviour than:

api reference:

https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf

and

https://www.adobe.com/devnet/acrobat/javascript.html

4: Another advice: try to simulate the user inputs.

Upvotes: 1

Related Questions