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