Search code examples
python-3.xpdftkintersavereportlab

reportlab doc.build(story) how to change output directory using asksaveasfilename tkinter?


I use reportlab lyibrary while creating tkinter app on Python. Method doc.build(story) saves PDF-file to current directory. But I want to push the button and save this file to the chosen directory by myself via asksaveasfilename of tkinter. How can I do that?

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)

As I said, method doc.build(story) saves PDF-file to current directory. I want to save in another

I tried to find a file path command inside of build method. But it doesn't exist


Solution

  • I have found the decision

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