Many of the answers here seem extremely out of date. This is especially so for the accepted answer, which uses pdftk. Pdftk is old (as of this edit, the latest release is from 2013), has terrible error handling, requires old versions of libraries, and is no longer packaged for ubuntu. Nobody in 2022 should be using pdftk for anything if they can possibly avoid it.
Qpdf is a nice open-source program that does many of the same things as pdftk, is still maintained (as of this edit, the latest commit is from 4 days ago) and it can do this task (using either --overlay
or --underlay
, depending on one's wishes):
qpdf a.pdf --overlay b.pdf -- c.pdf
[Edited to add] As a further example, here's a bit of ruby code using the prawn library to generate one example way this could be used.
The idea is to generate numbered labels for printing onto some hypothetical label sheet (represented by boxes.pdf
— actual dimensions are made up, but could be adjusted to fit an existing template if desired), and to have a version that shows the label dimensions visually, for on-screen review (boxednumbers.pdf
), while another version (numbers.pdf
) would have just the content to print onto an actual sheet of pre-cut labels.
(Note: Presumably in a real-life situation, boxes.pdf
might not be generated, and instead be a downloaded template from a label manufacturer — and the qpdf
command-line (as well as the dimensioning constants) would be adjusted accordingly, with the outer Prawn::Document.generate
block being removed, paper size possibly being modified, etc.)
#!/usr/bin/env ruby
require 'prawn'
require 'prawn/measurement_extensions'
# various constants to define the size and shape of things:
range = 1..90
columns = 5
col_width = 35.mm
box_height = 15.mm
margin = 2.mm
radius = 2.mm
# this is calculated for now, but it could be set manuallly:
font_size = box_height - 2*margin
# one document for showing the boxes (could use an existing PDF):
Prawn::Document.generate('boxes.pdf', page_size: 'A4') do |boxes|
# another that places numbers to be printed on top:
Prawn::Document.generate('numbers.pdf', page_size: 'A4') do |numbers|
range.each_with_index do |n, i|
# x and y for columner output:
x = (i % columns) * col_width
y = boxes.bounds.top - (i / columns) * box_height
# sizes of the boxes inside the columns:
width = col_width - margin
height = box_height - margin
# draw round rectangles in the boxes PDF:
boxes.stroke do
boxes.rounded_rectangle [x, y], width, height, radius
end
# draw numbers in the numbers PDF:
numbers.bounding_box [x,y], width: width, height: height do
numbers.text n.to_s, align: :center, valign: :center, size: font_size
end
end
end
end
# and then ask qpdf to merge them, with the boxes as an underlay:
%x(qpdf --underlay boxes.pdf -- numbers.pdf boxednumbers.pdf)