Various useful PDF manipulation commands

Posted on Thu 20 February 2020 in linux • 2 min read

Merging and rotating PDFs

Merging PDFs can be easily done with pdftk. You can also use this tool to select only specific pages from your document or rotate pages. This is my go-to tool if I don't have to manipulate pages beyond rotation.

To concatenate all PDFs in the working directory use

pdftk *.pdf cat output filename.pdf

To select only pages 1-3 and 5 from one document use

pdftk input.pdf cat 1-3 5 output filename.pdf

This even works with pages from multiple input files

pdftk A=input1.pdf B=other_file.pdf cat A1 A2 B7 B3 output filename.pdf

Rotation can be done with the rotate subcommand, to rotate page 4 by 180 degrees use

pdftk input.pdf rotate 4south output output.pdf

It is also possible to combine everything

pdftk A=input1.pdf B=other_file.pdf cat A1left B1left B2right output filename.pdf

See also the manpage for details.

Printing in special arrangements

Assuming you have a PDF and want to print that as a brochure or you want to print one A5 page two times on an A4 page. A useful tool for that is pdfjam, which you might already have installed. At least in Archlinux it is included in the texlive-core package.

Brochure or Book printing of a document

pdfbook input.pdf

You can also set the output format using pdfbook2 (which should be available using TeX Live) with pdfbook2 --paper=a5paper input.pdf to some paper format known to LaTex. Use the --short-edge option if you need short edge double sided printing (See also pdfbook2 --help).

Print single page A5 document two times on A4 sheet

pdfjam --nup 2x1 --landscape --outfile out.pdf input.pdf input.pdf

This can also be done as a script which handles input file rotation correctly

#!/bin/zsh

infile="$1"
outfile="$2"
[[ -z $infile ]] && echo 'Input file required!' && exit 2
[[ -z $outfile ]] && echo 'Output file required!' && exit 3
[[ $(pdfinfo $infile | grep Pages | grep -o '[0-9]\+') -gt 1 ]] && echo 'One single page documents!' && exit 1

wdir=$(mktemp -d)

dims=("${(@f)$(pdfinfo $infile | grep 'Page size' | grep -o '[0-9]\+\.[0-9]\+')}")
landscape=$(bc <<< "$dims[1] >= $dims[2]")

if [ $landscape -eq 1 ]
then
    pdfjam --angle 90 --fitpaper true --rotateoversize true --quiet --outfile $wdir/rot.pdf $infile
else
    cp $infile $wdir/rot.pdf
fi

pdfjam --nup 2x1 --landscape --quiet --outfile $wdir/out.pdf $wdir/rot.pdf $wdir/rot.pdf

if [ $landscape -eq 1 ]
then
    pdfjam --angle 270 --fitpaper true --rotateoversize true --quiet --outfile $outfile $wdir/out.pdf
else
    cp $wdir/out.pdf $outfile
fi

rm -rf $wdir

which can be used easily like

./a5-to-double-a4 input.pdf out.pdf

In the script above some rotation commands are also used: pdf90 and pdf270