|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +from PyPDF2 import PdfReader, PdfWriter |
| 4 | + |
| 5 | + |
| 6 | +def append_pdfs(input_pdf1, input_pdf2, output_pdf): |
| 7 | + """ |
| 8 | + Append two PDF files together. |
| 9 | +
|
| 10 | + Args: |
| 11 | + input_pdf1: Path to the first PDF file |
| 12 | + input_pdf2: Path to the second PDF file (will be appended) |
| 13 | + output_pdf: Path for the output merged PDF file |
| 14 | + """ |
| 15 | + # Create a PDF writer object |
| 16 | + writer = PdfWriter() |
| 17 | + |
| 18 | + # Read and add pages from the first PDF |
| 19 | + reader1 = PdfReader(input_pdf1) |
| 20 | + for page in reader1.pages: |
| 21 | + writer.add_page(page) |
| 22 | + |
| 23 | + # Read and add pages from the second PDF |
| 24 | + reader2 = PdfReader(input_pdf2) |
| 25 | + for page in reader2.pages: |
| 26 | + writer.add_page(page) |
| 27 | + |
| 28 | + # Write the merged PDF to output file |
| 29 | + with open(output_pdf, 'wb') as output_file: |
| 30 | + writer.write(output_file) |
| 31 | + |
| 32 | + print(f'{input_pdf1} + {input_pdf2} --> {output_pdf}') |
| 33 | + |
| 34 | + |
| 35 | +if __name__ == '__main__': |
| 36 | + import sys |
| 37 | + |
| 38 | + first_pdf, second_pdf, output_file = sys.argv[1:] |
| 39 | + |
| 40 | + try: |
| 41 | + append_pdfs(first_pdf, second_pdf, output_file) |
| 42 | + except FileNotFoundError as e: |
| 43 | + print(f'Error: Could not find PDF file - {e}') |
| 44 | + except Exception as e: |
| 45 | + print(f'Error: {e}') |
0 commit comments