[Tex/LaTex] Inject JavaScript with pdflatex etc. for page level events

javascriptpdftex

I am experimenting a little bit with JavaScript in PDF documents generated via pdflatex.

I wonder, whether there is a method to access the event handler of Adobe Acrobat or Acrobat Reader in order to react on certain events not just within a form, but for example on page level.

Although this is not a useful example for productivity, but how it is possible, to apply JavaScript code in a .tex file that plays a sound each time a (new) page is viewed within Acrobat Reader (or other PDF viewers if applicable)? This is connected to the page levels events Page Open/Close.

I know, this is something like a toy occupation for me (and others), but perhaps it could be of importance to other users as well.

The various documents on JavaScript provided by Adobe give no clue, except for directly using Adobe Acrobat (;-)), which has to be bought, however.

Best Answer

The page objects in a PDF listen to page open (/O) and close (/C) events.

Here is an example for using JavaScript actions (/S/JavaScript) with these events. Requires a recent media9 version and Adobe Reader X:

\documentclass{beamer}
\usepackage{media9}

%%%%%%%%% adjust this %%%%%%%%%%
\def\soundfile{sound_sample.mp3}
%%%%%%%% /adjust this %%%%%%%%%%

\pdfpageattr{/AA << %additional actions for pages
  %on every page open event, call ActionScript method 'play' exposed by APlayer.swf
  /O << /S/JavaScript /JS (annotRM['my_sound'].callAS('play');) >>
  %do something else on every page close event
  /C << /S/JavaScript /JS (app.alert('Page '+ this.pageNum + ' is being left.');) >>
>>}

\begin{document}

\begin{frame}{first frame \includemedia[
  label=my_sound,
  width=1ex, height=1ex,
  transparent,
  activate=pageopen, deactivate=onclick,
  addresource=\soundfile,
  flashvars={
    source=\soundfile
   &hideBar=true
  },
]{}{APlayer.swf}}
\dots
\end{frame}

\begin{frame}{other frame}
\dots
\end{frame}

\begin{frame}{yet another frame}
\dots
\end{frame}

\end{document}