This Python script merges all PDF files found within a specified directory into a single output PDF file using command-line arguments for configuration.
- Merges multiple PDF files into one.
- Sorts input PDF files alphabetically (A-Z) by default.
- Option to sort in reverse alphabetical order (Z-A).
- Configurable input directory, output directory, and output filename via command-line arguments.
- Provides default values for paths and filename if not specified.
- Includes error handling for file operations.
- Uses the
pypdf
library.
- Python 3.x
pypdf
library
- Clone the repository or download the script.
- Install the required library:
pip install pypdf
Navigate to the directory containing the script in your terminal and run it using Python. You can specify the input directory, output directory, and output filename using command-line arguments.
-input <path>
: Specifies the directory containing the PDF files to merge.- Default:
./pdfs
- Default:
-output <path>
: Specifies the directory where the merged PDF file will be saved. The directory will be created if it doesn't exist.- Default:
./output
- Default:
-name <filename>
: Specifies the name for the final merged PDF file.- Default:
merged_document.pdf
- Default:
-r
,--reverse
: Sorts the input PDF files in reverse alphabetical order (Z-A). If omitted, files are sorted alphabetically (A-Z).-h
,--help
: Displays the help message showing available options and exits.
-
Merge PDFs using default settings: (Assumes PDFs are in
./pdfs
, saves to./output/merged_document.pdf
, sorts A-Z)python pdf_merge.py
-
Specify input/output directories and filename:
python pdf_merge.py -input "/path/to/your/pdfs" -output "/path/to/save" -name "final_merged.pdf"
-
Specify paths and sort in reverse order (Z-A):
python pdf_merge.py -input "./my_pdfs" -output "./merged_files" -name "report_reversed.pdf" -r
or
python pdf_merge.py -input "./my_pdfs" -output "./merged_files" -name "report_reversed.pdf" --reverse
-
Display help:
python pdf_merge.py --help
The script will print:
- The directory it's searching for PDFs.
- The number of PDF files found.
- The sorting order being used (A-Z or Z-A).
- The name of each PDF file as it's being added to the merge process.
- A final confirmation message indicating the save location of the merged PDF, or error messages if issues occur.