7

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.

Daniel Silveira
  • 41,125
  • 36
  • 100
  • 121

3 Answers3

4

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/

Anson Smith
  • 6,194
  • 1
  • 23
  • 10
  • There is a simple example here: http://itextdocs.lowagie.com/tutorial/objects/anchors/index.php Look at the JavaScript section. – Anson Smith Oct 16 '08 at 20:44
3

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
Mark Storer
  • 15,672
  • 3
  • 42
  • 80
2

I've studied the PDF Specifications.

Turns out that the PDF file format isn't that hard.

It has a nice feature that allows you to modify the document just by appending new content in the end of the file.

If you are trying to do the same thing... don't be afraid! go and look at the specs.

Att Righ
  • 1,439
  • 1
  • 16
  • 29
Daniel Silveira
  • 41,125
  • 36
  • 100
  • 121
  • So you just append new and updated object streams followed by an updated Cross-Reference Table (xref) and trailer? Seems like you would need to be able to parse the existing object streams and calculate the byte offsets. – Daniel Ballinger Mar 28 '11 at 22:14