Thursday, August 03, 2006

Auto print on document load

Below is a simple process/hack to bypass the browser print dialog.
  • Generate a pdf for whatever(html or else) you want to print (This is typically done at the server. I use itext) using your fav api.
  • Once you have the pdf(from any source), you are 33% done.
  • Now we will ask the pdf to do something onLoad.
    • guess what "something" is: "Print"!
    • You can embed a piece of js in the pdf that will run at pdf load event.
    • In this js we will ask Acrobat reader to directly print the document to printer
  • Next you will have to load this pdf in an invisible iframe on your page, using javascript.
  • You are done! Trigger the invisible iframe load using either a button click or html-onLoad event. hurray your document is send straight to the printer!!!
  • This method works both in firefox and IE. It ha to, we are basically bypassing the browser security!
Here is the code that will embed javascript in the pdf document. Ofcourse, we will be using java and itext libs to do this.:

PdfReader pdfr = new PdfReader(pdfBytes);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

PdfStamper stamp = new PdfStamper(pdfr, baos);

stamp.addJavaScript("this.print({bUI: false, bSilent: false});\r");

stamp.close();



Loading pdf in an invisible frame is a easy task ... I would let you play arround with this code. Or may be I will post it if time permits!

1 Comments:

Blogger Fernando Boaglio said...

Great iText hack, thanks!

8:05 AM  

Post a Comment

<< Home