PDF overlays

Today I needed to combine two PDFs into one. Not by concatenating the pages; that would be easy using any number of apps, of which Preview is probably the most obvious. No, I had two single-page PDFs, each of which was meant to be printed on Avery 5161 label stock.

Avery 5161 labels

One of the PDFs had printing for the first three row of labels and the other had printing for the fourth and fifth rows. I could, of course, have printed the first page and then taken the sheet and fed it back through the printer for the second page, but I didn’t want to do it that way because

  1. Every time you pass label stock through a laser printer, it picks up a bit of toner on all the labels, making the remaining (unprinted upon) labels dingier.
  2. Where’s the fun in taking the easy way out?

What I wanted was to create a third PDF with all five rows on a single page, an overlay of the second PDF onto the first. There are ways to do this in PDFpenPro and PDF Expert, but a command-line solution seemed more efficient in the long run.1

For me, the Swiss Army knife of PDF manipulation is the so-called server version of PDFtk, so I checked its man page to see if it had an overlay command. It has two:

You might think these are redundant operations, but because of scaling, rotation, and transparency differences, you might find that one of these commands can do what you want and the other can’t. For the PDFs I was working with, either would do.

The command that did what I wanted was

pdftk first.pdf stamp second.pdf output labels.pdf

I then printed labels.pdf and got all the labels in a single pass through the printer. To cut down on the amount of typing I’d need to do in the future, I made a simple script,2 called overlay:

#bash
#!/bin/bash

pdftk "$1" stamp "$2" output -

Now I can use this command with a syntax similar to cat:

overlay first.pdf second.pdf > labels.pdf

To make it really like cat, I’d have to generalize overlay to handle any number of inputs, not just two. I’ll leave that, as the math textbooks like to say, as an exercise for the reader.


  1. And there is a long run. I’ve had this situation come up before where I either did the two-passes-through-the-printer thing or used a GUI app to make the combined PDF. It was time to create an automated solution. 

  2. Thanks to Vitor Galvão for reminding me to wrap the argument placeholders in double quotes. I always forget that.