I use a lot of forms at work. The more paperless the office gets, the more paper we generate. Every school has its own physical exam form, every government agency has its own application form, every screening test is another form for the parent to fill out. And my handwriting is atrocious. So I try to get PDF copies of everything, then use PDF Escape to add text boxes that I can fill in, and an image of my signature at the bottom. But when filling them out, that still leaves a lot of either typing or cut-and-paste from the EMR (electronic medical record) of the patient's name, birthdate, address etc. There had to be a better way, and one that uses only free tools (I'm not buying Acrobat for $400).
Fortunately, Adobe Reader can run a version of Javascript, and we can use that to help fill in the form.
Every PDF includes a /Catalog
object that serves as the root object of the document. Normally it just includes a reference to the array of pages, but it can include other things like Javascript to be executed when the document is opened. The syntax is convoluted; it is a dictionary containing a dictionary containing a string:
0 1 obj
<<
/Type /Catalog
/Pages 0 2 R % a standard catalog entry
/Names << % the Javascript entry
/JavaScript <<
/Names [
(EmbeddedJS)
<<
/S /JavaScript
/JS (
app.alert('Hello, World!');
)
>>
]
>>
>> % end of the javascript entry
>>
endobj
That's complicated but the coding part is straightforward: take an existing PDF, open it in a text editor and find /Catalog
and insert the boilerplate after the /Pages
reference, and put in your code. PDF is smart enough to match parentheses, so as long as your code pairs them correctly (you don't have any strings like "We love smileys :)"
) you don't have to escape them. If you need to, escape them with a backslash. Actual backslashes in your code need to be escaped (write them as \\
, since the PDF parser will read the string before interpreting it as Javascript.
This will create an incorrect PDF file, since the xref table no longer has the correct byte lengths. Adobe Reader will correct this automatically, as will PDF Escape, but they compress and otherwise munge up the code so it's impossible to further edit.
See a sample blank page that says "Hello, World".
Continue reading ‘Adding Javascript to PDF Files’ »