Embed javascript in pdf (autoprint)

456 views
Skip to first unread message

j

unread,
Oct 25, 2016, 6:55:38 AM10/25/16
to jsreport
I'm trying to generate a pdf report that automatically loads the print dialog when the file is opened.

It's possible to do this using javascript embdedded in a pdf but is it possible to to use phantom-pdf to embed javascript in to a pdf?

Specifically I want to modify this object:

10 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj

By adding this javascript:

10 0 obj
<<
/Type /Catalog
/Pages 2 0 R
 
/Names <<
   
/JavaScript <<
      /
Names [
       
(EmbeddedJS)
       
<<
         
/S /JavaScript
         
/JS (
           
print(true);
         
)
       
>>
     
]
   
>>
 
>>
>>
endobj

Jan Blaha

unread,
Oct 25, 2016, 8:31:44 AM10/25/16
to jsreport, jos...@gmail.com
phantomjs cannot do such a thing. However we can post-process the pdf output with script and add the code you are posting.

See the working version here

Btw thank you for this. I had no idea this can be so easily done. Can I ask where did found the code for printing? Maybe there are other nice tricks...

jos...@gmail.com

unread,
Oct 25, 2016, 9:40:11 AM10/25/16
to jsreport, jos...@gmail.com
Thanks for this!

I have been banging my head against a wall trying various flawed methods of autoprinting a pdf.

Your afterRender method works really well, except if using "tasks": { "strategy": "in-process" } where I get the error "Error occured - Error during rendering report: must start with number, buffer, array or string". Is it possible to make this work with that strategy?

Adding javascript to a pdf seems like a fairly poorly documented feature. Looks like you can use normal javascript, though obviously dom access is different.

I adapted this from the code here, which also has examples of modifying the document: http://bililite.com/blog/2012/06/06/adding-javascript-to-pdf-files/

Jan Blaha

unread,
Oct 25, 2016, 10:05:12 AM10/25/16
to jsreport, jos...@gmail.com
It can be considered a bug, it should be the same for all strategies. For now, just change the function like this for in-process

function afterRender(req, res, done) {
    var originalString = res.content.toString('binary')
    var replacedString = originalString.replace('/Pages 2 0 R', PRINT_CODE)
    
    res.content = new Buffer(replacedString, 'binary')
    done()
}

Thank you for the link, there is a url to official adobe js reference with 800 pages, it will be nice reading. I hope it can dramatically change the jsreport options and power.
Reply all
Reply to author
Forward
0 new messages