Created
March 9, 2026 09:07
-
-
Save ShijianXu/d105a2469964548ac8492ee1a2f5d38e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import os | |
| from pypdf import PdfWriter | |
| from pathlib import Path | |
| def merge_pdfs_in_folder(folder_path: str, output_path: str = "merged.pdf") -> None: | |
| """ | |
| Merge all PDF files in a folder (sorted by filename) into a single PDF. | |
| Uses pypdf (modern version). | |
| Args: | |
| folder_path (str): Path to the folder containing PDF files. | |
| output_path (str): Path for the merged output PDF. | |
| """ | |
| folder = Path(folder_path) | |
| if not folder.is_dir(): | |
| raise ValueError(f"Not a directory: {folder_path}") | |
| # Collect all *.pdf files (case-insensitive), sort them | |
| pdf_files = sorted( | |
| [p for p in folder.iterdir() if p.is_file() and p.suffix.lower() == ".pdf"], | |
| key=lambda p: p.name.lower() | |
| ) | |
| if not pdf_files: | |
| print("No PDF files found in the folder.") | |
| return | |
| writer = PdfWriter() | |
| for pdf_path in pdf_files: | |
| print(f"Appending {pdf_path.name}") | |
| # The append method will open, read, and close the file internally | |
| writer.append(pdf_path) | |
| # Write the combined PDF | |
| # Ensure parent directory of output exists | |
| output = Path(output_path) | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| writer.write(output) | |
| writer.close() | |
| print(f"Merged {len(pdf_files)} PDFs into '{output}'") | |
| if __name__ == "__main__": | |
| folder = '/Path/pdfs' | |
| output = '/Path/merged.pdf' | |
| merge_pdfs_in_folder(folder, output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment