Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Programmatically Inject JavaScript in PDF files?

Tags:

javascript

pdf

How to Programmatically Inject JavaScript in PDF files?

Can it be done without Adobe Professional?


My goal is: I want to show up the print dialog immediately when I open the PDF.

I know that this can be done with JavaScript code embedded in the document.

like image 644
Daniel Silveira Avatar asked Oct 16 '08 19:10

Daniel Silveira


People also ask

Can a PDF contain JavaScript?

NitroPDF and Adobe Acrobat definitely support JavaScript in PDF files.

Can PDF run scripts?

A PDF can have any number of Document Level scripts. These scripts are the first ones executed when the document is opened in Acrobat or Adobe Reader.


2 Answers

If you're developing in Java have a look at iText: http://www.lowagie.com/iText/ I think it supports what you are looking for.

There are also some .Net versions around: http://www.ujihara.jp/iTextdotNET/en/

like image 71
Anson Smith Avatar answered Sep 27 '22 22:09

Anson Smith


iText (and iText_Sharp_) are quite capable of adding JS to an existing PDF... page actions, links, document level script, you name it.

The JavaDoc can be found here.

This was written with Java in mind, but the C# code would look almost identical (if not exactly the same, with the exception handling stripped out like this).

PdfReader myReader = new PdfReader( myFilePath ); // throws IOException
PdfStamper myStamper = new PdfStamper( myReader, new FileOutputStream(outPath) ); // throws IOE, DocumentException

// add a document script
myStamper.addJavaScript( myScriptString );

// add a page-open script, 1 is the first page, not zero0
PdfAction jsAction = PdfAction.javaScript( someScriptString );
myStamper.setPageAction( PdfWriter.PAGE_OPEN, jsAction, myStamper.getWriter(), pageNumber ); // throws PdfException (for bad first param)

PdfFormField button = PdfFormField.createButton(myWriter, PdfFormField.FF_PUSHBUTTON);
button.setWidget( myRectangle, PdfAnnotation.HIGHLIGHT_INVERT );

// the important part, adding jsAction
jsAction = PdfAction.javaScript( buttonScriptString );
button.setAdditionalActions( PdfAnnotation.AA_DOWN, jsAction ); // mouse down

myStamper.addAnnotation( pageNum, button );

myStamper.close(); // write everything out, throws DocumentException, IOE
like image 31
Mark Storer Avatar answered Sep 27 '22 23:09

Mark Storer