How to inline bold a text for a pdf generated with FPDF in Python using a font that supports Unicode UTF-8

572 Views Asked by At

I am making a Python script to generate a PDF document with FPDF2, I have a problem when rendering this document, in one of the paragraphs some words and phrases must be in bold, I had managed to solve this problem using multi-cell and activating the MARKDOWN, or using write_html() everything worked perfectly until in one of the texts that I have saved in a .txt format that I am using to make the PDF the unicode character " appears, throwing the following error:

fpdf.errors.FPDFUnicodeEncodingException: Character "“" at index 544 in text is outside the range of characters supported by the font used: "times". Please consider using a Unicode font.

The next thing I did was download a font from Google fonts and add it with add_font()

texto1 = f"""**{nombre}**, mayor de edad, vecino de **{ciudad_usuario}**, identificado con la **{id_tipo}**
 No. **{id_numero}** expedida en **{id_lugar_expedicion}**, actuando con mi propio nombre y ... """
fuente_tipo = "SourceSerifPro-Regular"
class PDF(FPDF):
    def __init__(self):
        FPDF.__init__(self, unit="mm", format="letter", orientation="P")
        self.add_font("SourceSerifPro-Regular", "", "SourceSerifPro-Regular.ttf")
    
    def header(self):
        self.set_xy(25, 10)
        self.set_font(fuente_tipo, '', 12)
        self.ln(15)
        self.cell(0, 10, fecha, 0)
        self.ln(15)
    
    def footer(self):
        self.set_xy(185, -15)
        self.set_font(family= fuente_tipo, size= 8)
        self.cell(0, 10, 'Página ' + str(self.page_no()) + ' de n', 0)

    def add_txt_text(self, route):
        with open(route, "r", encoding="utf-8") as f:
            texto = f.read()
        self.multi_cell(0, None, texto, markdown = True, new_x='LEFT', new_y= 'NEXT')

pdf = PDF()
pdf.set_margins(25, 30, 10)
pdf.add_page()
pdf.set_auto_page_break(auto=True, margin=20)
pdf.set_font(fuente_tipo, '', 12)
pdf.multi_cell(0, None,  texto1, markdown = True, new_x='LEFT', new_y= 'NEXT') # max_line_height=30,
# This text has a unicode caracter
pdf.add_txt_text('fundamento_juridico.txt')
pdf.output('ejemplo.pdf')

FDPF has 3 default fonts, which do not support some utf-8 characters, as soon as I add the Google font it throws the following error.

 File "C:\Users\user\Documents\PDF_generator\index.py", line 101, in <module>
    pdf.multi_cell(0, None,  texto1, markdown = True, new_x='LEFT', new_y= 'NEXT') # max_line_height=30,
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\fpdf\fpdf.py", line 216, in wrapper
    return fn(self, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\fpdf\fpdf.py", line 3213, in multi_cell
    styled_text_fragments = self._preload_font_styles(normalized_string, markdown)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\fpdf\fpdf.py", line 3004, in _preload_font_styles     
    self.set_font(style="B")
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\fpdf\fpdf.py", line 1873, in set_font
    raise FPDFException(
fpdf.errors.FPDFException: Undefined font: sourceserifpro-regularB - Use built-in fonts or FPDF.add_font() beforehand

Now I see myself between eliminating those types of characters in the texts that I use to generate the pdf, or not being able to use in-line bold in some texts. Any advice or solution to this problem is appreciated.

I want to make a pdf in which I can add some text I have, and I want to be able to do in-line bold and use Unicode characters, also I want that when the text reach the bottom margin it creates another page.

0

There are 0 best solutions below