« Scanning with Brother DCP-7065DN in Ubuntu | Home | ImageMagick snippet: batch crop, dither, and guillotine »
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 | 5 Comments »
January 18th, 2025 at 23:53
… [Trackback]
[…] There you will find 95382 more Info on that Topic: compdigitec.com/labs/2020/10/10/concatenating-pdfs-while-padding-extending-odd-length-pdfs/ […]
January 23rd, 2025 at 19:58
… [Trackback]
[…] Find More here on that Topic: compdigitec.com/labs/2020/10/10/concatenating-pdfs-while-padding-extending-odd-length-pdfs/ […]
January 25th, 2025 at 16:06
… [Trackback]
[…] Information to that Topic: compdigitec.com/labs/2020/10/10/concatenating-pdfs-while-padding-extending-odd-length-pdfs/ […]
February 3rd, 2025 at 19:58
… [Trackback]
[…] Here you can find 7261 more Info on that Topic: compdigitec.com/labs/2020/10/10/concatenating-pdfs-while-padding-extending-odd-length-pdfs/ […]
February 6th, 2025 at 07:12
… [Trackback]
[…] Find More Information here on that Topic: compdigitec.com/labs/2020/10/10/concatenating-pdfs-while-padding-extending-odd-length-pdfs/ […]