Print to network printer from PHP Print to network printer from PHP php php

Print to network printer from PHP


This is a tough nut to crack. I've had my own adventures in Windows printing from Ruby and came up with a few potential solutions that work by invoking an external command, which in PHP-land is system() or exec() (don't forget escapeshellcmd()/escapeshellarg()—they tend to make this stuff easier, especially on Windows). All of them assume Windows knows about the printer and it can be referenced by name.

  1. You can literally just redirect the file to the networked printer, e.g.:

    copy /b \path\to\filename.pdf > \\Printer_Machine\Printer_Queue

    The /b switch specifies a binary file, but I'm 80% sure it's not strictly now,in 2012.

  2. You can try the print command:

    print /d:\\Printer_Machine\Printer_Queue \path\to\filename.pdf

    \d stands for "device." I haven't actually tried this one and I'm not sure if itworks with PDF or only, owing to its DOS origins, text files.

  3. Install Adobe Reader and use its command line facilities:

    AcroRd32.exe /t \path\to\filename.pdf "Printer Name" "Driver Name" "Port Name"

    I'm not sure if your server environment can accommodate Reader but this is thesolution I've been most successful with. You can finddocumentation here(PDF, pg. 24). Printer Name and Driver Name should match exactly what you see in the printer's properties in Control Panel. Port_Name can usually be omitted, I think.

  4. Print using Ghostscript. I've never tried this onWindows but thedocumentation is here and there'smore info here. Thecommand goes something like this:

    gswin32.exe -sDEVICE=mswinpr2 -sOutputFile="%printer%Printer Name" \path\to\filename.pdf

    mswinpr2 refers to Windows' own print drivers (see the second link above),"%printer%" is literal and required and "Printer Name" should, again, match theprinter's name from Control Panel exactly. Ghostscript has many, many options andyou'll likely have to spend some time configuring them.

Finally, a general tip: You can register a network printer with a device name with the net use command e.g.:

C:\> net use LPT2 \\Printer_Machine\Printer_Queue /persistent:yes

This should let you use LPT2 or LPT2: in place of \\Printer_... with most commands.

I hope that's helpful!


Not sure if this works for all printers but this gets the job done sending ZPL files to a Zebra label printer:

<?php if(($conn = fsockopen('192.168.10.112',9100,$errno,$errstr))===false){    echo 'Connection Failed' . $errno . $errstr;}$data = <<<HERE    ^XA    ^FT50,200    ^A0N,200,200^FDTEST^FS    ^FT50,500    ^A0N,200,200^FDZebra Printer^FS    ^XZHERE;#send request$fput = fputs($conn, $data, strlen($data));#close the connectionfclose($conn);?>