Friday, January 20, 2012

Add Javascript to Existing PDF files (Python)

There are several tools on the net, that helps you to add javascript to new PDF files - but I could not find any tool to add Javascript to existing PDF files.

Here is a python script that accomplishes that. For this you need to install the following python package (which is a modified pyPDF - found at The modified pyPDF is found at Or you could simply unzip the modified pyPDF in your current directory.

Help text and Usage for this script:
$ python 
Usage: [options] in-pdf-file out-pdf-file

  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -j JAVASCRIPT, --javascript=JAVASCRIPT
                        javascript to embed (default embedded JavaScript is
                        app.alert messagebox)
                        javascript file to embed

  add-js-to-pdf, use it to add embedded JavaScript to a PDF document that will execute automatically when the document is opened
  Based on modified pyPDF and inspiration from


Here is the
from pyPdf import PdfFileWriter, PdfFileReader

import optparse

def Main():
    """add-js-to-pdf, use it to add embedded JavaScript to a PDF document that will execute automatically when the document is opened

    parser = optparse.OptionParser(usage='usage: %prog [options] in-pdf-file out-pdf-file', version='%prog 0.1')
    parser.add_option('-j', '--javascript', help='javascript to embed (default embedded JavaScript is app.alert messagebox)')
    parser.add_option('-f', '--javascriptfile', help='javascript file to embed')
    (options, args) = parser.parse_args()

    if len(args) != 2:
        print ''
        print '  add-js-to-pdf, use it to add embedded JavaScript to a PDF document that will execute automatically when the document is opened'
        print '  Based on modified pyPDF and inspiration from'
        print ''

    input1 = PdfFileReader(file(args[0], "rb"))
    output = PdfFileWriter()
    pages = input1.getNumPages()
    for p in range(pages):
    if options.javascript == None and options.javascriptfile == None:
            javascript = """app.alert({cMsg: 'Hello from PDF JavaScript', cTitle: 'Testing PDF JavaScript', nIcon: 3});"""
    elif options.javascript != None:
            javascript = options.javascript
            fileJavasScript = open(options.javascriptfile, 'rb')
            print "error opening file %s" % options.javascriptfile

            javascript =
            print "error reading file %s" % options.javascriptfile

    outputStream = file(args[1], "wb")

if __name__ == '__main__':


  1. Very easy to understand post, but i still have a question. When I do a document.close(), I get an error "The document has no pages". I
    am not sure, what I am doing wrong.

    1. @Tom: Can you post (or email) the code that you are using? There is no document.close() in the above code nor do I understand why a .close() at any of the above code places can throw that error. -- Moorthy rsmoorthy at

  2. Hi there! Thanks for your post.

    I was wondering if it is possible to programmatically add page-level javascript (instead of document level javascript) to a PDF.. perhaps with pyPDF or any other library you're aware of?

    I need to add page-open javascript to a whole bunch of PDF's. Unfortunately I'm not able to use document-level javascript because I'm using 3D annotations and I can't get a handle on those at document open.

    - Arvind

  3. This is because all browsers have accepted all browsers have accepted JavaScript as a scripting language for them and provides integrated support for it. All you need to do is to handle some of the tasks that are dependent on DOM of different browser properly.
    best web design tutorials

  4. This online pdf merger or pdf combiner or pdf joiner will easily merge pdf files together with use of any software or any registration. pdf joiner

  5. A decent programming will hold every one of the parts of the first record flawless. Something else to note while purchasing a PDF converter is the cost. altocompresspdf

  6. We are truly thankful for your blog entry. You will discover a great deal of methodologies in the wake of going to your post. I was precisely scanning for. A debt of gratitude is in order for such post and please keep it up.
    convert pdf to jpg online free

  7. Casino Tycoon, Inc. Announces Plans to Launch Las Vegas
    Casino Tycoon, Inc. (COO: MEGADRIVE) 목포 출장샵 announces plans to launch Las Vegas casino 광명 출장샵 of 경상북도 출장안마 the Las 창원 출장샵 Vegas Strip and Las Vegas Strip with casinos 용인 출장마사지