|
| 1 | +import fitz # PyMuPDF |
| 2 | +import argparse |
| 3 | +import sys |
| 4 | +import os |
| 5 | + |
| 6 | + |
| 7 | +def add_frame(input_pdf_path, left=20, right=20, top=20, bottom=20, thickness=2): |
| 8 | + try: |
| 9 | + doc = fitz.open(input_pdf_path) |
| 10 | + |
| 11 | + for page in doc: |
| 12 | + page_rect = page.rect |
| 13 | + frame_rect = fitz.Rect( |
| 14 | + left, # left |
| 15 | + top, # top |
| 16 | + page_rect.width - right, # right |
| 17 | + page_rect.height - bottom # bottom |
| 18 | + ) |
| 19 | + |
| 20 | + page.draw_rect( |
| 21 | + frame_rect, |
| 22 | + width=thickness |
| 23 | + ) |
| 24 | + |
| 25 | + base, _ = os.path.splitext(input_pdf_path) |
| 26 | + output_pdf_path = f"{base}_framed.pdf" |
| 27 | + doc.save(output_pdf_path) |
| 28 | + print(f"PDF with rectangle frame saved to {output_pdf_path}") |
| 29 | + |
| 30 | + except UnicodeDecodeError: |
| 31 | + print( |
| 32 | + "Error: Input file path encoding issue. " |
| 33 | + "Please ensure the file path is UTF-8 encoded." |
| 34 | + ) |
| 35 | + except Exception as e: |
| 36 | + print(f"An error occurred: {e}") |
| 37 | + finally: |
| 38 | + if 'doc' in locals(): |
| 39 | + doc.close() |
| 40 | + |
| 41 | + |
| 42 | +def main(): |
| 43 | + parser = argparse.ArgumentParser( |
| 44 | + description=( |
| 45 | + "Add a rectangle frame to each page of a PDF document.\n" |
| 46 | + "Flags: --l (left), --r (right), --t (top), --b (bottom), " |
| 47 | + "--th (thickness)" |
| 48 | + ), |
| 49 | + formatter_class=argparse.RawTextHelpFormatter |
| 50 | + ) |
| 51 | + parser.add_argument("input_pdf", help="Path to the input PDF file") |
| 52 | + parser.add_argument("--l", type=float, default=20, help="Left margin") |
| 53 | + parser.add_argument("--r", type=float, default=20, help="Right margin") |
| 54 | + parser.add_argument("--t", type=float, default=20, help="Top margin") |
| 55 | + parser.add_argument("--b", type=float, default=20, help="Bottom margin") |
| 56 | + parser.add_argument("--th", type=float, default=2, help="Frame thickness") |
| 57 | + |
| 58 | + try: |
| 59 | + args = parser.parse_args() |
| 60 | + add_frame( |
| 61 | + args.input_pdf, |
| 62 | + left=args.l, |
| 63 | + right=args.r, |
| 64 | + top=args.t, |
| 65 | + bottom=args.b, |
| 66 | + thickness=args.th |
| 67 | + ) |
| 68 | + except Exception as e: |
| 69 | + print(f"Error: {e}\n") |
| 70 | + parser.print_usage() |
| 71 | + sys.exit(1) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + main() |
0 commit comments