pyfpdf icon indicating copy to clipboard operation
pyfpdf copied to clipboard

Setting font with write_html

Open boludo00 opened this issue 6 years ago • 5 comments

I am trying to create a pdf from a HTML string because I have some styling to do (bold fonts for titles, etc) Formatting looks fine however, the resulting font is the standard HTML font and no matter what I do, it doesn't seem to change the font. Is it possible to use both the write_html method and modify font?

heres a snippet of what I was trying to do: class MyFPDF(FPDF, HTMLMixin): pass pdf = MyFPDF() html = """<p style="font-family: arial">Text</p>""" pdf.write_html(html) The resulting pdf does not reflect the change in font. Any pointers appreciated!

boludo00 avatar Oct 22 '18 17:10 boludo00

So this library doesn't actually render html, even though it uses a standard html parser (from the standard library), you can search here and see which attributes it respects by searching in the text for attrs, and style is not one of them from what i understand after a cursory reading. If you need fine-grained html rendering, I would try to use https://wkhtmltopdf.org/

alexanderankin avatar Oct 22 '18 18:10 alexanderankin

I was able to change the font in the html by overriding the HTML2FPDF constructor, it defaults to Times New Roman so that was the issue.

boludo00 avatar Oct 22 '18 18:10 boludo00

I have the same issue @boludo00 . Can you write some exact instructions here on how to do this? Thanks!

ayya-vimala avatar Dec 26 '21 09:12 ayya-vimala

I got it working with a custom font (you can do it with predefined fonts as well). Here is how:

pdf = FPDF()
# Have the .ttf file available in the same directory
pdf.add_font('Manrope', 'B', 'Manrope-Regular.ttf', uni=True)
pdf.add_page()
# The html_str is exactly as the html code below
pdf.add_html(html_str)
pdf.output("fonts_in_html_example.pdf")

Where the HTML text added via FPDF is the following

<font face="Manrope">
  <table>
    ...  
  </table>
</font>

The documentation is a bit lackluster. There are some more tags that can be used, that are documented here: https://pyfpdf.readthedocs.io/en/latest/reference/write_html/index.html

andreehultgren avatar Jan 18 '23 11:01 andreehultgren

Hi @andreehultgren

Note that PyFPDF is not maintained anymore. fpdf2 is its successor: https://pypi.org/project/fpdf2/ You will find the list of HTML tags supported there: https://pyfpdf.github.io/fpdf2/HTML.html

Lucas-C avatar Jan 18 '23 13:01 Lucas-C