Untitled
unknown
plain_text
a year ago
2.7 kB
7
Indexable
import csv
from fpdf import FPDF
class PDF(FPDF):
def basic_table(self, headings, rows):
for heading in headings:
self.cell(w=4, h=0.7, txt=heading, border=1)
self.ln()
for row in rows:
for col in row:
self.cell(w=4, h=0.6, txt=col, border=1)
self.ln()
def improved_table(self, headings, rows, col_widths=(4.2, 3.9, 3.5, 4.0)):
for col_width, heading in zip(col_widths, headings):
self.cell(w=col_width, h=0.7, txt=heading, border=1, align="C")
self.ln()
for row in rows:
for col_width, col in zip(col_widths, row):
self.cell(w=col_width, h=0.6, txt=col, border="LR", align="R" if col_width == col_widths[-1] else "L")
self.ln()
self.cell(w=sum(col_widths), h=0, txt="", border="T")
def colored_table(self, headings, rows, col_widths=(4.2, 3.9, 3.5, 4.2)):
# Cabeçalho em vermelho
self.set_fill_color(255, 0, 0) # Vermelho
self.set_text_color(255) # Texto em branco
self.set_draw_color(255, 0, 0) # Bordas vermelhas
self.set_line_width(0.03)
self.set_font(style="B")
for col_width, heading in zip(col_widths, headings):
self.cell(col_width, 0.7, heading, border=1, align="C", fill=True)
self.ln()
# Linhas de dados em azul claro
self.set_fill_color(173, 216, 230) # Azul claro
self.set_text_color(0) # Texto em preto
self.set_font()
fill = False
for row in rows:
for col_width, col in zip(col_widths, row):
self.cell(col_width, 0.6, col, border="LR", align="L" if col_width == col_widths[0] else "R", fill=fill)
self.ln()
fill = not fill # Alterna entre linhas preenchidas e não preenchidas
self.cell(sum(col_widths), 0, "", "T")
def load_data_from_csv(csv_filepath):
headings, rows = [], []
with open(csv_filepath, encoding="utf8") as csv_file:
for row in csv.reader(csv_file, delimiter=","):
if not headings: # Extraindo nomes das colunas da primeira linha
headings = row
else:
rows.append(row)
return headings, rows
# Exemplo de uso
csv_filepath = "countries.txt" # Certifique-se de que o arquivo existe neste local
col_names, data = load_data_from_csv(csv_filepath)
pdf = PDF(unit='cm')
pdf.set_font("helvetica", size=14)
pdf.add_page()
pdf.basic_table(col_names, data)
pdf.add_page()
pdf.improved_table(col_names, data)
pdf.add_page()
pdf.colored_table(col_names, data)
pdf.output("demo.pdf")Editor is loading...
Leave a Comment