How to Programmatically Inject JavaScript in PDF files?

后端 未结 3 510
囚心锁ツ
囚心锁ツ 2021-01-02 18:24

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 immed

3条回答
  •  长发绾君心
    2021-01-02 19:07

    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
    

提交回复
热议问题