Compdigitec Labs

« | Home | »

Concatenating PDFs while padding/extending odd-length PDFs

By admin | October 10, 2020

When concatenating PDFs to consolidate print jobs, it is nice to have single-page or PDFs with odd numbers of pages to not have to share sides with another unrelated document.

There is a short script available at ; however, it does not appear to be updated for PyPDF2. So here is an update for Python3 and PyPDF2.


sudo apt install python3-pypdf2

#!/usr/bin/env python3
# Inspired from

import copy
import sys
from PyPDF2 import PdfFileWriter, PdfFileReader

def main():
    if len(sys.argv) < 2:
        print("No input PDFs specified", file=sys.stderr)
        return 1

    pdf_writer = PdfFileWriter()
    output_page_number = 0
    alignment = 2           # to align on even pages

    # So we can close the file objects later.
    file_objects = []

    for filename in sys.argv[1:]:
        # Store the file object for closing
        f = open(filename, 'rb')

        # Open the input PDF
        pdf_reader = PdfFileReader(f)

        # Add input pages
        for page in pdf_reader.pages:
            output_page_number += 1

        # Add filler pages
        while output_page_number % alignment != 0:
            output_page_number += 1

    # Write output PDF while input files are still open.

    # Close open files.
    while len(file_objects) > 0:

    return 0


If you found this article helpful or interesting, please help Compdigitec spread the word. Don’t forget to subscribe to Compdigitec Labs for more useful and interesting articles!

Topics: Linux | 1 Comment »

One Response to “Concatenating PDFs while padding/extending odd-length PDFs”

  1. go x honolulu Says:
    March 29th, 2024 at 23:51

    … [Trackback]

    […] Find More on that Topic: […]