Categories We Write About

Build a PDF merger_splitter tool

Here’s a simple yet functional Python-based PDF merger and splitter tool using the PyPDF2 library. This script provides a basic command-line interface for users to:

  • Merge multiple PDFs into one.

  • Split a PDF into individual pages or by a page range.

python
import os from PyPDF2 import PdfReader, PdfWriter def merge_pdfs(pdf_list, output_path): pdf_writer = PdfWriter() for pdf in pdf_list: reader = PdfReader(pdf) for page in reader.pages: pdf_writer.add_page(page) with open(output_path, 'wb') as out: pdf_writer.write(out) print(f"Merged PDF saved to: {output_path}") def split_pdf(pdf_path, output_dir, split_ranges=None): reader = PdfReader(pdf_path) if not os.path.exists(output_dir): os.makedirs(output_dir) if split_ranges: for i, (start, end) in enumerate(split_ranges, start=1): writer = PdfWriter() for page_num in range(start-1, end): writer.add_page(reader.pages[page_num]) output_file = os.path.join(output_dir, f"split_{i}.pdf") with open(output_file, 'wb') as out: writer.write(out) print(f"Saved split: {output_file}") else: for i, page in enumerate(reader.pages, start=1): writer = PdfWriter() writer.add_page(page) output_file = os.path.join(output_dir, f"page_{i}.pdf") with open(output_file, 'wb') as out: writer.write(out) print(f"Saved page: {output_file}") def main(): print("PDF Merger/Splitter Tool") print("1. Merge PDFs") print("2. Split PDF") choice = input("Select an option (1 or 2): ") if choice == '1': pdf_list = input("Enter PDF paths to merge (comma separated): ").split(',') pdf_list = [pdf.strip() for pdf in pdf_list] output_path = input("Enter output PDF path: ").strip() merge_pdfs(pdf_list, output_path) elif choice == '2': pdf_path = input("Enter PDF path to split: ").strip() output_dir = input("Enter output directory for split PDFs: ").strip() custom_split = input("Split by page ranges? (y/n): ").strip().lower() split_ranges = None if custom_split == 'y': split_input = input("Enter page ranges (e.g., 1-3,4-5): ") split_ranges = [tuple(map(int, r.split('-'))) for r in split_input.split(',')] split_pdf(pdf_path, output_dir, split_ranges) else: print("Invalid option.") if __name__ == "__main__": main()

Instructions:

  1. Install PyPDF2:

    bash
    pip install PyPDF2
  2. Save the script as pdf_tool.py.

  3. Run the script:

    bash
    python pdf_tool.py

This tool can be enhanced with a GUI using libraries like tkinter or PyQt if needed. Let me know if you’d like a web or GUI version.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About