Skip to content
Advertisement

Prompt user to choose the name and location when saving a pdf (python)

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.

import PyPDF2 
 
# Open the files that have to be merged one by one
pdf1File = open(filepath, 'rb')
pdf2File = open('Summary_output.pdf', 'rb')
 
# Read the files that you have opened
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
 
# Create a new PdfFileWriter object which represents a blank PDF document
pdfWriter = PyPDF2.PdfFileWriter()

# Loop through all the pagenumbers for the first document
for pageNum in range(pdf1Reader.numPages):
    pageObj = pdf1Reader.getPage(pageNum)
    pdfWriter.addPage(pageObj)
 
# Loop through all the pagenumbers for the second document
for pageNum in range(pdf2Reader.numPages):
    pageObj = pdf2Reader.getPage(pageNum)
    pdfWriter.addPage(pageObj)
 
# Now that you have copied all the pages in both the documents, write them into the a new document
pdfOutputFile = open('MergedFiles.pdf', 'wb')
pdfWriter.write(pdfOutputFile)
 
# Close all the files - Created as well as opened
pdfOutputFile.close()
pdf1File.close()
pdf2File.close()

Advertisement

Answer

You can do this with a tkinter filedialog.

root = tk.Tk()
root.withdraw()

pdfPath = filedialog.asksaveasfilename(defaultextension = "*.pdf", filetypes = (("PDF Files", "*.pdf"),))
if pdfPath: #If the user didn't close the dialog window
    pdfOutputFile = open(pdfPath, 'wb')
    pdfWriter.write(pdfOutputFile)
    pdfOutputFile.close()
    pdf1File.close()
    pdf2File.close()

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement