I have implemented a simple table using library tabulate, am now attempting to print this table that has table format fancy_grid
using fpdf but am getting the following error, how can I add this table to the pdf??
Error
File "E:DevelopementDesktop ApplicationsGuiWithWxvenvlibsite-packagesfpdffpdf.py", line 1170, in _putpages
p = self.pages[n].encode("latin1") if PY3K else self.pages[n]
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 388-425: ordinal not in range(256)
The Table
My Code
from fpdf import FPDF
from tabulate import tabulate
import webbrowser
def pdf_Example_Two():
title = '20000 Leagues Under the Seas'
class PDF(FPDF):
def header(self):
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Calculate width of title and position
w = self.get_string_width(title) + 6
self.set_x((210 - w) / 2)
# Colors of frame, background and text
self.set_draw_color(0, 80, 180)
self.set_fill_color(230, 230, 0)
self.set_text_color(220, 50, 50)
# Thickness of frame (1 mm)
self.set_line_width(1)
# Title
self.cell(w, 9, title, 1, 1, 'C', 1)
# Line break
self.ln(10)
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Text color in gray
self.set_text_color(128)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()), 0, 0, 'C')
def chapter_title(self, num, label):
# Arial 12
self.set_font('Arial', '', 12)
# Background color
self.set_fill_color(200, 220, 255)
# Title
self.cell(0, 6, 'Chapter %d : %s' % (num, label), 0, 1, 'L', 1)
# Line break
self.ln(4)
def chapter_body(self, name):
# Read text file
with open(name, 'rb') as fh:
txt = fh.read().decode('utf-8')
# Times 12
self.set_font('Times', '', 12)
# Output justified text
self.multi_cell(0, 5, txt)
# Line break
self.ln()
# Mention in italics
self.set_font('', 'I')
self.cell(0, 5, '(end of excerpt)')
def print_chapter(self, num, title, name):
self.add_page()
self.chapter_title(num, title)
self.chapter_body(name)
l = [["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = tabulate(l, headers=['Name', 'Age', 'University'], tablefmt='fancy_grid', showindex="always")
print(table)
print('
')
with open("C:\Users\John\Desktop\kaita.txt", "w", encoding="utf-8") as outf:
outf.write(table)
pdf = PDF()
pdf.set_title(title)
pdf.set_author('Jules Verne')
pdf.print_chapter(1, 'A RUNAWAY REEF', 'C:\Users\John\Desktop\kaita.txt')
pdf.output('tuto3.pdf', 'F')
webbrowser.open_new(f"tuto3.pdf")
pdf_Example_Two()
question from:
https://stackoverflow.com/questions/66062457/how-to-add-tabulate-table-into-pdf-page-using-fpdf