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 https://unix.stackexchange.com/questions/66418/how-can-i-merge-pdf-files-so-that-each-file-begins-on-an-odd-page-number ; however, it does not appear to be updated for PyPDF2. So here is an update for Python3 and PyPDF2.

Prep:

sudo apt install python3-pypdf2

#!/usr/bin/env python3
# Inspired from https://unix.stackexchange.com/a/66455

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.
    # https://stackoverflow.com/questions/44375872/pypdf2-returning-blank-pdf-after-copy
    file_objects = []

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

        # Open the input PDF
        pdf_reader = PdfFileReader(f)

        # Add input pages
        for page in pdf_reader.pages:
            pdf_writer.addPage(page)
            output_page_number += 1

        # Add filler pages
        while output_page_number % alignment != 0:
            pdf_writer.addBlankPage()
            output_page_number += 1

    # Write output PDF while input files are still open.
    pdf_writer.write(sys.stdout.buffer)

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

    return 0

sys.exit(main())

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 | No Comments »

Comments