How can I change my code so I can save my final pdf (MergedFiles.pdf) with a name chosen by the user and in a location chosen by them. I would like to have a popup(maybe tkinter?) that will give the user the option of choosing the name and location to save the pdf file.
JavaScript
x
32
32
1
import PyPDF2
2
3
# Open the files that have to be merged one by one
4
pdf1File = open(filepath, 'rb')
5
pdf2File = open('Summary_output.pdf', 'rb')
6
7
# Read the files that you have opened
8
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
9
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
10
11
# Create a new PdfFileWriter object which represents a blank PDF document
12
pdfWriter = PyPDF2.PdfFileWriter()
13
14
# Loop through all the pagenumbers for the first document
15
for pageNum in range(pdf1Reader.numPages):
16
pageObj = pdf1Reader.getPage(pageNum)
17
pdfWriter.addPage(pageObj)
18
19
# Loop through all the pagenumbers for the second document
20
for pageNum in range(pdf2Reader.numPages):
21
pageObj = pdf2Reader.getPage(pageNum)
22
pdfWriter.addPage(pageObj)
23
24
# Now that you have copied all the pages in both the documents, write them into the a new document
25
pdfOutputFile = open('MergedFiles.pdf', 'wb')
26
pdfWriter.write(pdfOutputFile)
27
28
# Close all the files - Created as well as opened
29
pdfOutputFile.close()
30
pdf1File.close()
31
pdf2File.close()
32
Advertisement
Answer
You can do this with a tkinter filedialog
.
JavaScript
1
11
11
1
root = tk.Tk()
2
root.withdraw()
3
4
pdfPath = filedialog.asksaveasfilename(defaultextension = "*.pdf", filetypes = (("PDF Files", "*.pdf"),))
5
if pdfPath: #If the user didn't close the dialog window
6
pdfOutputFile = open(pdfPath, 'wb')
7
pdfWriter.write(pdfOutputFile)
8
pdfOutputFile.close()
9
pdf1File.close()
10
pdf2File.close()
11
Firstly, it creates and hides a tkinter window. If you didn’t do this an empty window would come up when you launched the file dialog. Then it uses filedialog.asksaveasfilename
to launch the native OS file dialog. I’ve specified that it should ask for PDF files only. Then the if statement checks if a path has been returned, if it has it follows the same process as before.