Printing without the Dialog

Apr09
Missing Image
By SiteCrafting Staff

One day, one of our clients came to us with a very unusual request - they wanted to be able to print something directly from the browser, but without displaying the usual print dialog box. I don't have much time in the webdev business, but I've never heard of this kind of request, and neither had anyone else in the office.


Initially, we didn't think that it was possible. The browser File > Print command uses a dialog box. So does the javascript print() function. The only reason that we knew this was possible was that the client's current system was already doing it. With a little research, we figured out how to print directly from the browser without displaying a dialog box.

Tools you'll need:
1 local Unix or Linux server
A pinch of Javascript
1 PHP exec() call
PHP to format your data

First: your server MUST be a local server, on the same network as the printer. This is because we'll be using the lp command to shoot off the print job.

Second, to get this to work from the browser, you need a little javascript to call a file using XMLHttpRequest that will call the lp command and execute the print job.

The actual command to start off the print job looks something like this:
lpr -p printer file.txt
The final ingredient of this system is to use PHP to format the data you need to print, and then save it to a file. The lpr command then works on that file.

In the end, we were able to get this whole thing working, but only because Dustin over at out co-location facility knew what needed to be done. Part of the command line printing involves manually creating a print spool - a task not for the faint of heart. The spool is defined in /etc/printcap, and looks something like this:

printer:
        :ml=0:
        :mx=0:
        :sd=/var/spool/lpd/printer:
        :af=/var/spool/lpd/printer/printer.acct:
        :sh:
        :rm=XXX.XXX.XXX.XXX:
        :rp=text:
        :if=/etc/magicfilter/ibmpro-filter:
        :lpd_bounce=true:

Replace the XXX string with your printer's IP address. Then, when you click on a print button, the javascript fires off the XMLHttpRequest, which calls the PHP script to create the print file, and executes the command to print that file. Or, you can call the script with a PHP function on a page load.

Shout outs to Dustin and Andrzej, for making the printing work, and for getting the scripts to call the print action.



Dev

Back To Feed