Automatically print a PDF generated with ReportLab using JavaScript

It seems everyone is asking how to embed JavaScript in a PDF created with ReportLab.

Google also use this PDF feature to allow for printing of proprietary office documents from their Gmail service. Google's method is somewhat different and they bind the JavaScript to the first object in the document and trigger it by referencing it with the Names entity as shown below.

%PDF-1.4
%âãÏÓ
1 0 obj
<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>
endobj
2 0 obj
<</Names[(0000000000000000) 1 0 R]>>
endobj
3 0 obj

I was not able to use the Google method with ReportLab, however after a few frustrating hours spent reverse engineering the PDF specification, and a trip to the PDF Standard (ISO 32000 documentation) I was successful after some inspiration from an unlikely source.

Just include the following before you generate your pdf. And it should just work:

from reportlab.pdfbase import pdfdoc
pdfdoc.PDFCatalog.OpenAction = '<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>'

NB. ReportLab 2.5 Has a typo. Change OpenActions to OpenAction.

diff -r tmp/lib/python2.7/site-packages/reportlab/pdfbase/pdfdoc.py lib/python2.7/site-packages/reportlab/pdfbase/pdfdoc.py
1022c1022
<         Dests Outlines Pages Threads AcroForm Names OpenAction PageMode URI
---
>         Dests Outlines Pages Threads AcroForm Names OpenActions PageMode URI

If you would like to see a working example of this then checkout Barcode Printing for Django app on Github.

I hope this saves you some time!

— Andrew


Next entry

Previous entry

Related entries

Similar entries


Comments

No comments yet.


Pingbacks

Pingbacks are open.


Post your comment





Site theme originally by styleshout.com