DEV Community

Cover image for Merge PDF files with QPDF
Dr. Gernot Starke
Dr. Gernot Starke

Posted on

Merge PDF files with QPDF

The Problem

You want to merge (concatenate) several PDF files.
It is not possible to just append one PDF after the other, let's say by command-line append operations.

Other simple PDF utilities fail in preserving internal hyperlinks (cross references).

I needed a programatic solution that works completely automated (controlled via make) within a Docker container.

Nerdy Solution

QPDF is an extensively documented tool for:

"structural, content-preserving transformations on PDF files."
(from their website)

One (very basic) use case is merging two or more PDF files into one single output file.
To be more specific: I want to add a cover page to the main part of a book, as illustrated below.

merge cover with book

I write the book in Markdown and use a TeX-based toolchain to generate PDF output (that's another story).

The book itself contains numerous cross-references (internal links), pointing to other sections of the book or to specific pages. These links must be preserved during merge - and my initial approaches lost all those links.

QPDF to the rescue:



qpdf book.pdf --pages cover.pdf 1 book.pdf 1-z -- result.pdf  


Enter fullscreen mode Exit fullscreen mode

It took me a while to figure out the exact syntax - and wrote this post so I (and other lost book-writing soules) can find it later.

Beware, though...

I suggest to keep the dimensions of book- and cover page identical (obviously you will care for that anyway).

Manual Solution, MacOS only

In case you are working on MacOS, you can simply use the preview tool to concatenate PDF files - in most cases hyperlinks and cross-references are preserved.
But: It is a manual solution.

Thanx

Thanx to the awesome Jay Berkenbilt for creating and maintaining QPDF since 2005 (!!).

Thanx to Wesley Tingey for the cover image, via Unsplash.

Top comments (0)