About me: My name is Solène Rapenne, pronouns she/her. I like learning and sharing knowledge. Hobbies: '(BSD OpenBSD Qubes OS Lisp cmdline gaming security QubesOS internet-stuff). I love percent and lambda characters. Qubes OS core team member, former OpenBSD developer solene@. No AI is involved in this blog.

Contact me: solene at dataswamp dot org or @solene@bsd.network (mastodon).

I'm a freelance OpenBSD, FreeBSD, Linux and Qubes OS consultant, this includes DevOps, DevSecOps, technical writing or documentation work. If you enjoy this blog, you can sponsor my open source work financially so I can write this blog and contribute to Free Software as my daily job.

Manipulate PDF files easily with pdftk

Written by Solène, on 19 August 2023.
Tags: #productivity

Comments on Fediverse/Mastodon

1. Introduction §

I often need to work with PDF, sometimes I need to extract a single page, or add a page, too often I need to rotate pages.

Fortunately, there is a pretty awesome tool to do all of these tasks, it's called PDFtk.

pdftkofficial project website

2. Operations §

Pdftk command line isn't the most obvious out there, but it's not that hard.

2.1. Extracting a page §

Extracting a page requires the cat sub command, and we need to give a page number or a range of pages.

For instance, extracting the pages 11, and from 16 to 18 from the file my_pdf.pdf to a new file export.pdf can be done with the following command:

pdftk my_pdf.pdf cat 11 16-18 output export.pdf

2.2. Merging PDF into a single PDF §

Merging multiple PDFs into a single PDF also uses the sub command cat. In the following example, you will concatenate the PDF first.pdf and second.pdf into a merged.pdf result:

pdftk first.pdf second.pdf cat output merged.pdf

Note that they are concatenated in their order in the command line.

2.3. Rotating PDF §

Pdftk comes with a very powerful way to rotate PDFs pages. You can specify pages or ranges of pages to rotate, the whole document, or only odd/even pages etc...

If you want to rotate all the pages of a PDF clockwise (east), we need to specify a range 1-end, which means first to last page:

pdftk input.pdf rotate 1-endeast output rotated.pdf

If you want to select even or odd pages, you can add the keyword even or odd between the range and the rotation direction: 1-10oddwest or 2-8eveneast are valid rotations.

2.4. Reversing the page ordering §

If you want to reverse how pages are in your PDF, we can use the special range end-1 which will go through pages from the last to the first one, with the sub command cat this will only recreate a new PDF:

pdftk input.pdf cat end-1 output reversed.pdf

3. Conclusion §

Pdftk have some other commands, most people will need to extract / merge / rotate pages, but take a look at the documentation to learn about all pdftk features.

PDF are usually a pain to work with, but pdftk make it very fast and easy to apply transformation on them. What a great tool :-)