Untitled
from fpdf import FPDF class PDF(FPDF): def header(self): self.set_font('Arial', 'B', 12) self.cell(0, 10, 'Sample Table', 0, 1, 'C') def footer(self): self.set_y(-15) self.set_font('Arial', 'I', 8) self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C') def chapter_title(self, title): self.set_font('Arial', 'B', 12) self.cell(0, 10, title, 0, 1, 'L') self.ln(4) def chapter_body(self, body): self.set_font('Arial', '', 12) self.multi_cell(0, 10, body) self.ln() def add_table(self, data): self.set_font('Arial', 'B', 12) col_widths = [40, 40, 40] # Adjust column widths as needed # Print table header self.cell(col_widths[0], 10, 'Name', 1) self.cell(col_widths[1], 10, 'Age', 1) self.cell(col_widths[2], 10, 'Percentage', 1) self.ln() # Print table rows self.set_font('Arial', '', 12) for row in data: self.cell(col_widths[0], 10, row[0], 1) self.cell(col_widths[1], 10, str(row[1]), 1) self.cell(col_widths[2], 10, str(row[2]), 1) self.ln() def main(): # Sample data data = [ ['Artan', 30, 40], ['Besa', 40, 15], ['Ilir', 35, 25], ['Andi', 28, 20] ] # Create PDF pdf = PDF() pdf.add_page() # Add title pdf.chapter_title('Data Table') # Add table pdf.add_table(data) # Save PDF filepath = 'table.pdf' pdf.output(filepath) print(f"PDF saved as {filepath}") if __name__ == '__main__': main()
Leave a Comment