Home > Software engineering >  Python script to merge PDF files with a blank page
Python script to merge PDF files with a blank page

Time:11-03

I have the following script compiled from other's suggestions, but I can't seem to get it to run properly. I need to merge several 3 page bill files into a single file for printing while adding a blank page in between each bill file so that each bill prints properly (we don't want the first page of one bill printed on the back of the previous bill).

# If the file errors with "no module PyPDF2" then from command line, run pip install PyPDF2
import os
from os import listdir, mkdir, startfile
from os.path import isfile, join, exists
from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter

#Input file path and print the pdf files in that path
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
    print(file)

def add_blank_to_end(pdffiles: list) -> list:
    names = []
    for f in pdffiles:
        pdf_in = open(f, 'rb')
        pdf_file = PdfFileReader(pdf_in)
        output = PdfFileWriter()
        output.appendPagesFromReader(pdf_file)
        output.addBlankPage()
        names.append(f'b{f}')
        outputStream = open(f'b{f}', 'wb')
        output.write(outputStream)
    return names

#Append the pdf files
def merge_pdfs(pdffiles: list):
    merger = PdfFileMerger()
    for f in pdffiles:
        merger.append(f)
    merger.write("document-output.pdf")

with_blank = add_blank_to_end(pdffiles)
merge_pdfs(with_blank)

CodePudding user response:

# If the file errors with "no module PyPDF2" then from command line, run pip install PyPDF2
import os
from os import listdir, mkdir, startfile
from os.path import isfile, join, exists
from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter

#Input file path and print the pdf files in that path
path = input("Enter the folder location")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
    print(file)

def add_blank_to_end(pdffiles: list) -> list:
    names = []
    for f in pdffiles:
        pdf_in = open(path '/' f, 'rb')
        pdf_file = PdfFileReader(pdf_in)
        output = PdfFileWriter()
        output.appendPagesFromReader(pdf_file)
        output.addBlankPage()
        names.append(f'b{f}')
        outputStream = open(f'b{f}', 'wb')
        output.write(outputStream)
    return names

def merge_pdfs(pdffiles: list):
    merger = PdfFileMerger()
    for f in pdffiles:
        merger.append(f)
    merger.write("document-output.pdf")

with_blank = add_blank_to_end(pdffiles)
merge_pdfs(with_blank)
  • Related