python-3.x reportlab doc.build(story)如何使用asksaveasfilename tkinter更改输出目录?

0qx6xfy6  于 2023-05-19  发布在  Python
关注(0)|答案(1)|浏览(116)

我在Python上创建tkinter应用程序时使用了reportlab liibrary。方法doc.build(story)将PDF文件保存到当前目录。但是我想按下按钮,通过tkinter的asksaveasfilename将这个文件保存到自己选择的目录。我该怎么做?

def save_as_pdf(self, file_path=None):
        pdfmetrics.registerFont(TTFont('DejaVuSerif', 'DejaVuSerif.ttf'))
        doc = SimpleDocTemplate(f"{self.current_friend}_computers.pdf", pagesize=letter)
        story = []

        data= [self.table_computers.item(row_id)['values'] for row_id in self.table_computers.get_children()]
        
        tblstyle = TableStyle([('FONT', (0, 0), (-1, len(data)-1), 'DejaVuSerif', 12)])
        tbl = Table(data)
        tbl.setStyle(tblstyle)
        story.append(tbl)
        if file_path is None:
            file_path = asksaveasfilename(
                filetypes=(
                    ("PDF-файл", "*.pdf"),
                    ("All files", "*.*"),
                ),
                initialfile=(f"{self.current_friend}_computers.pdf"),
            )
        print(file_path)
        doc.build(story)

正如我所说的,方法doc.build(story)将PDF文件保存到当前目录。我想保存到另一个
我试图在build方法中找到一个文件路径命令。但它并不存在

qni6mghb

qni6mghb1#

我已经找到了决定

def save_as_pdf(self, file_path=None):
    pdf_file =BytesIO()
    pdfmetrics.registerFont(TTFont('DejaVuSerif', 'DejaVuSerif.ttf'))
    doc = SimpleDocTemplate(pdf_file, pagesize=letter)
    story = []
    

    data= [self.table_computers.item(row_id)['values'] for row_id in self.table_computers.get_children()]
    
    data.append([f'У вашего друга {self.current_friend} следующие компьютеры: '])
    data.reverse()
    
    tblstyle = TableStyle([('FONT', (0, 0), (-1, len(data)-1), 'DejaVuSerif', 12)])
    tbl = Table(data)
    tbl.setStyle(tblstyle)
    story.append(tbl)
    if file_path is None:
        file_path = asksaveasfilename(
            filetypes=(
                ("PDF-файл", "*.pdf"),
                ("All files", "*.*"),
            ),
            initialfile=(f"{self.current_friend}_computers.pdf"),
        )
    doc.build(story)
    pdf_file.seek(0)
    with open(file_path, 'wb') as f:
            f.write(pdf_file.getbuffer())

相关问题