2020-04-27 Printing from pdf-tools

Some time ago I studied the command-line interface to CUPS. Of course, my goal from the beginning was to use Emacs, not the terminal. It turns out that setting the default printer using lpoptions is not enough for pdf-misc-print-document (bound to C-c C-p in pdf-tools) to work. This command tries first to locate one of three tools for command-line printing: gtklp, xpp and gpr. Frankly, I’ve never heard about any of them, and I just wanted to use lp. This is easy to accomplish – you just need to set the variable pdf-misc-print-programm (sic!) to "lp" and you’re good to go.

However, what about my 2-up printing? At least gtklp (which I briefly looked into) lets you select lots of print options, at the expense of a suboptimal UI (as the name suggests, it is a graphical tool).

It turns out that you can set the arguments for lp in the variable pdf-misc-print-programm-args (as a list of strings). The only thing that remains is to make Emacs somehow ask for those arguments every time (or at least, every time you use the prefix argument).

Of course, we could just define another command and bind it to C-c C-p in pdfview mode – but there is a better way. We can advise the pdf-misc-print-document function (I have written about advising functions before).

What we want here is to check for C-u and if it was supplied, ask the user for any additional arguments to lp, and put them temporarily into pdf-misc-print-programm-args.

(defun pdf-misc-print-possibly-with-args (orig-fun filename &optional interactive-p)
  "Advice for `pdf-misc-print-document' to use args for `lp'."
  (let ((pdf-misc-print-programm-args
	 (append pdf-misc-print-programm-args
		 (when current-prefix-arg
		   (split-string (read-string "Additional arguments for lp: "))))))
    (funcall orig-fun filename interactive-p)))

(advice-add 'pdf-misc-print-document :around #'pdf-misc-print-possibly-with-args)

This code is pretty much self-explanatory. We use Elisp’s dynamic binding here – if our advised function was called with a prefix argument, we effectively add arguments read from the minibuffer to pdf-misc-print-programm-args, and call pdf-misc-print-document with the value of that variable temporarily changed.

The only remaining problem with this code is remembering what arguments does lp accept. But this is another story, and I’m going to cover it another time.

CategoryEnglish, CategoryBlog, CategoryEmacs