Lauch JavaScript in PDF Form at startup (generated with hyperref)

Viewed 133

I have a PDF Form with a read-only calculated TextField. This PDF is generated from a Latex code using the hyperref package.

To illustrate my problem, let's use this MWE (from the pdftex and javascript forms with automatic calculations question) :
Result
enter image description here

Latex

\documentclass{article}
\usepackage{hyperref}[pdftex]

\begin{document}
\begin{Form}

\TextField[maxlen=40,align=2,height=10pt,width=45pt,name=alpha,default=5]{Alpha}

\bigskip
\TextField[maxlen=40,align=2,height=10pt,width=45pt,name=beta,default=4]{Beta}

\bigskip
\TextField[
  maxlen=40,
  calculate={%
    var f_alpha = this.getField("alpha");
    var f_beta = this.getField("beta");
    event.value = f_alpha.value + f_beta.value;
  },
   align=2,height=10pt,width=45pt,name=gamma,readonly=true]{Gamma}
\end{Form}
\end{document}

My problem is that at startup, the Gamma value is not calculated (9 in our case). I have to change any field in the form for all JavaScript to update.

Is there a way for all javascript to be executed when the file is launched and not just when it is modified?

1 Answers

Solution

The JavaScript scripts in the PDF are not executed by default when the file is opened.
However, Adobe Acrobat allows us to define events and actions in a PDF. (e.g. open a file, play a sound, go to a page). It is also possible to execute a JavaScript script when an event occurs.
The calculateNow() function of the doc will recalculate all the fields in the document.
However, this function should not be executed when the file is opened because the order of creation of the fields is not defined. It is possible that the calculateNow() function is called when some of the fields have not yet been created.
This script should only be run when the first page is opened (and not when the file is opened). It has therefore finished being generated.

To write this action in LaTeX, you need to use the \pdfpageattr command:

\pdfpageattr{/AA << %additional actions for pages
    %on every page open event (/O), add a JavaScript action
    /O << /S/JavaScript /JS (this.calculateNow();) >>
  >>}
MWE
\documentclass{article}
\usepackage{hyperref}[pdftex]

\pdfpageattr{/AA << %additional actions for pages
    %on every page open event (/O), add a JavaScript action
    /O << /S/JavaScript /JS (this.calculateNow();) >>
  >>}

\begin{document}
\begin{Form}

  \TextField[maxlen=40,align=2,height=10pt,width=45pt,name=alpha,default=5]{Alpha}

  \bigskip
  \TextField[maxlen=40,align=2,height=10pt,width=45pt,name=beta,default=4]{Beta}

  \bigskip
  \TextField[
    maxlen=40,
    calculate={%
        var f_alpha = this.getField("alpha");
        var f_beta = this.getField("beta");
        event.value = f_alpha.value + f_beta.value;
      },
    align=2,height=10pt,width=45pt,name=gamma,readonly=true]{Gamma}
\end{Form}
\end{document}
Related