Tuesday, September 20, 2011

Duplex Printing from the Command Line to an HP LaserJet Printer

My department has several HP LaserJet printers available to access within the department via LPR and SMB. However, if you are working from a personal laptop connected to the university wireless, those servers will not be available to you. Instead, you must print by piping your documents through SSH to a department server that does have access.

Unfortunately, doing duplex printing (i.e., two-sided printing) to an HP LaserJet printer from the command line is not trivial. So, using the GSview documentation as a guide, I put together a small bash script (available for download as hplj_duplex_print) that does the trick.
#!/bin/bash

declare -a input_file
if test $# -eq 0; then
    input_file=("-")
else
    input_file=("$@")
fi

( echo -e "\e%-12345X@PJL JOB"
  echo "@PJL ENTER LANGUAGE = POSTSCRIPT"
  echo "<< /Duplex true /Tumble false >> setpagedevice"
  gs -sDEVICE=psmono -sPAPERSIZE=letter -q -sOutputFile=- \
    -dNOPAUSE -dBATCH "${input_file[@]}"
  echo -e "\e%-12345X@PJL EOJ"
  echo -e "\e%12345X"
  ) | lp -d your_HP_printer_spool_name
You should replace the your_HP_printer_spool_name with your printer's spool name. You might want to tweak some of the options (details below), but the general structure will remain the same. The opening and closing escape sequences communicate to the HP LaserJet printer that a PostScript file is coming. Then the setpagedevice PostScript directive instructs the printer to use its duplex module.

Regarding tweaking:
  • Again, make sure to change your_HP_printer_spool_name to your spool name. You may also want to change lp to lpr, but you will likely have to change -d to -P then.
  • You may want to change the gs (GhostScript) options to suit your purposes. For example, you can change the psmono device to one of the other GhostScript devices like psgray or psrgb.
  • The Tumble switch determines whether to do short-edge (true) or long-edge (false) duplex printing, and so this script defaults to the latter case. If you prefer vertical flipping, change the /Tumble false to /Tumble true. You might also make this a configurable command-line switch on the script.

No comments: