|
7 | 7 | from PyPDF2 import PdfFileReader, PdfFileWriter
|
8 | 8 |
|
9 | 9 | # let the user choose an input file
|
10 |
| -input_file_name = gui.fileopenbox("", "Select a PDF to trim...", "*.pdf") |
11 |
| -if input_file_name is None: # exit on "Cancel" |
| 10 | +input_file_path = gui.fileopenbox("", "Select a PDF to trim...", "*.pdf") |
| 11 | +if input_file_path is None: # exit on "Cancel" |
12 | 12 | exit()
|
13 | 13 |
|
14 | 14 | # get the page length of the input file
|
15 |
| -input_file = PdfFileReader(open(input_file_name, "rb")) |
| 15 | +input_file = PdfFileReader(input_file_path) |
16 | 16 | total_pages = input_file.getNumPages()
|
17 | 17 |
|
18 | 18 | # let the user choose a beginning page
|
|
62 | 62 | exit()
|
63 | 63 |
|
64 | 64 | # let the user choose an output file name
|
65 |
| -output_file_name = gui.filesavebox("", "Save the trimmed PDF as...", "*.pdf") |
66 |
| -while input_file_name == output_file_name: # cannot use same file as input |
| 65 | +output_file_path = gui.filesavebox("", "Save the trimmed PDF as...", "*.pdf") |
| 66 | +while input_file_path == output_file_path: # cannot use same file as input |
67 | 67 | gui.msgbox(
|
68 | 68 | "Cannot overwrite original file!", "Please choose another file..."
|
69 | 69 | )
|
70 |
| - output_file_name = gui.filesavebox( |
| 70 | + output_file_path = gui.filesavebox( |
71 | 71 | "", "Save the trimmed PDF as...", "*.pdf"
|
72 | 72 | )
|
73 |
| -if output_file_name is None: |
| 73 | +if output_file_path is None: |
74 | 74 | exit() # exit on "Cancel"
|
75 | 75 |
|
76 | 76 | # read in file, write new file with trimmed page range and save the new file
|
|
79 | 79 | for page_num in range(int(page_start) - 1, int(page_end)):
|
80 | 80 | page = input_file.getPage(page_num)
|
81 | 81 | output_PDF.addPage(page)
|
82 |
| -output_file = open(output_file_name, "wb") |
83 |
| -output_PDF.write(output_file) |
84 |
| -output_file.close() |
| 82 | + |
| 83 | +with open(output_file_path, "wb") as output_file: |
| 84 | + output_PDF.write(output_file) |
| 85 | + |
0 commit comments