Created
June 4, 2020 19:36
-
-
Save justengel/b0df74f381dc304bce8cd6eeb0ed7a17 to your computer and use it in GitHub Desktop.
Merge multiple pdf files into one pdf file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Merge multiple pdf files into one pdf file. | |
Args: | |
f (list/str): List of filenames to merge | |
out (str): Save filename to merge all of the files into. | |
Requires: | |
* pip install PyPDF2 | |
""" | |
import os | |
import sys | |
# print(sys.executable) | |
import glob | |
import argparse | |
from PyPDF2 import PdfFileMerger | |
def merge(files, out=None): | |
if len(files) == 0: | |
raise ValueError('At least 1 file is required!') | |
elif not all(isinstance(f, str) and f.lower().endswith('.pdf') for f in files): | |
raise TypeError('All of the given files must be a string filename with a ".pdf" extension.') | |
if out is None: | |
f_split = os.path.splitext(files[0]) | |
out = ''.join((f_split[0], '_merged', f_split[1])) | |
merger = PdfFileMerger() | |
# Check if files in directory or glob pattern | |
if len(files) == 1: | |
if os.path.isdir(files[0]): | |
files = glob.glob(os.path.join(files[0], '*.pdf')) | |
elif '*' in files[0]: | |
files = glob.glob(files[0]) | |
# merge the files | |
for pdf in files: | |
merger.append(pdf) | |
merger.write(out) | |
merger.close() | |
return out | |
if __name__ == "__main__": | |
P = argparse.ArgumentParser(description='Merge PDF files') | |
P.add_argument('files', nargs='*', type=str, help="PDF file names to merge") | |
P.add_argument('--out', '-o', default=None, type=str, help='Output file name. If not given the first filename with _merged will be used.') | |
ARGS = P.parse_args() | |
files = ARGS.files | |
out = ARGS.out | |
if len(files) == 0: | |
# Ask for file names | |
files = [] | |
while True: | |
f = input('Enter a file path (leave blank to stop): ').strip() | |
if f: | |
files.append(f) | |
else: | |
break | |
if not out: | |
out = input('Enter a safe filename (leave blank for auto): ').strip() or None | |
out = merge(files, out=out) | |
print('File saved to ', out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment