保存 pdf 时提示用户选择名称和位置 (python)

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

如何更改我的代码,以便我可以使用用户选择的名称和他们选择的位置保存我的最终 pdf (MergedFiles.pdf)。我想要一个弹出窗口(也许是 tkinter?),让用户可以选择保存 pdf 文件的名称和位置。

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()

您可以使用 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()

首先,它创建并隐藏了一个 tkinter window。如果你不这样做,当你启动文件对话框时,一个空的 window 会出现。然后它使用 filedialog.asksaveasfilename 启动本机 OS 文件对话框。我已经指定它应该只要求 PDF 文件。然后 if 语句检查是否已返回路径,如果有则遵循与之前相同的过程。