首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >保存pdf时提示用户选择名称和位置(python)

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

Stack Overflow用户
提问于 2021-07-20 06:51:19
回答 1查看 43关注 0票数 1

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

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-20 07:19:14

你可以用一个tkinter filedialog来做这件事。

代码语言:javascript
复制
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窗口。如果您没有这样做,当您启动文件对话框时,将出现一个空窗口。然后,它使用filedialog.asksaveasfilename启动本机OS文件对话框。我已经指定它应该只请求PDF文件。然后if语句检查是否返回了路径,如果有,则遵循与前面相同的过程。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68447801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档