Extracting and Merging PDF Pages on Linux

guide

While filling out an online application, I needed to upload three months of bank statements as one PDF. Each statement contained multiple pages, but I only needed the page with the balances, keeping the transactions out of it. So I needed to extract the necessary pages and merge them back into one PDF.

Since the statements contain financial information, I wanted to keep the process local rather than use an online PDF merger. I also didn’t need a full PDF editor for such a task. I used lightweight, readily available command-line utilities from poppler-utils for extracting and merging, and qpdf to deal with an encryption error.

Extracting the pages

pdfseparate extracts pages from a PDF into individual files. It’s included in Poppler’s poppler-utils package, which also provides pdfunite and pdfinfo.

On many Linux distros, the poppler-utils package is already available. If it’s not, it can be installed with:

sudo apt install poppler-utils

Imagine the statements are named july.pdf, aug.pdf, and sept.pdf. We extract their first pages as follows:

pdfseparate -f 1 -l 1 july.pdf july-page-%d.pdf
pdfseparate -f 1 -l 1 aug.pdf aug-page-%d.pdf
pdfseparate -f 1 -l 1 sept.pdf sept-page-%d.pdf

-f 1 sets the first page to extract, and -l 1 sets the last. Since both are page one, each command produces a single-page PDF. The %d in the output filename is replaced with the page number, so aug-page-%d.pdf becomes aug-page-1.pdf.

The original statements aren’t modified. The output consists of three smaller PDFs containing only the selected pages.

Merging the documents

pdfunite combines complete PDF files in the order given:

pdfunite july-page-1.pdf aug-page-1.pdf sept-page-1.pdf submission.pdf

The first three filenames are the inputs. submission.pdf, the last filename, is the new document.

But the merge failed:

Unimplemented Feature: Could not merge encrypted files ('aug-page-1.pdf')

The encrypted PDF

pdfinfo can show whether a PDF is encrypted:

pdfinfo aug-page-1.pdf | grep '^Encrypted:'

pdfinfo prints information about the file. The pipe (|) passes that output to grep, which keeps only the line beginning with Encrypted:. An encrypted file reports yes on that line.

I used qpdf to create an unencrypted copy. On Debian or Ubuntu, it’s available as a small command-line package:

sudo apt install qpdf

Using the extracted pages:

qpdf --decrypt  july-page-1.pdf july-page-1-clear.pdf
qpdf --decrypt  aug-page-1.pdf aug-page-1-clear.pdf
qpdf --decrypt  sept-page-1.pdf sept-page-1-clear.pdf

--decrypt writes the output without PDF encryption. The original xxx-page-1.pdf stays unchanged; xxx-page-1-clear.pdf is the new copy.

The merge then used the new unencrypted copies:

pdfunite july-page-1-clear.pdf aug-page-1-clear.pdf sept-page-1-clear.pdf submission.pdf

References