javascriptpdfghostscriptpostscript

Does Ghostscript support inserting JavaScript into an existing PDF?


I do not find anything related in the documentation: https://www.ghostscript.com/doc/current/Use.htm

I did find a somewhat related example for inserting watermarks on each page, so it seems like it may be possible.

Is it possible in Ghostscript to add watermark to every page in PDF

However, it's not clear from that example how to insert Javascript.


Solution

  • If you want to execute JavaScript on document load you can do it like this (thanks to this useful PDF primer).

    [ /_objdef {MyAlert} /type /dict /OBJ pdfmark
    [ {MyAlert} << /JavaScript << /Names [ (MyAlertCode) << /S /JavaScript
    /JS (app.alert\("Hello world 1."\);app.alert\("Hello world 2."\);) >> ]
    >> >>
    /PUT pdfmark
    [ {Catalog} << /Names {MyAlert} >> /PUT pdfmark
    

    Full steps to reproduce would be:

    1. Make sure Ghostscript is installed on your computer (the gs command)
    2. Put your source PDF in a folder alongside a postscript (.ps) file that contains the code from above.
    3. cd into that folder
    4. Run: gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=newpdf.pdf myps.ps mypdf.pdf (obviously replace myps.ps and mypdf.pdf with your actual file names).
    5. Open newpdf.pdf to verify that it worked!

    Other tips:

    Resources: