pyfpdf
pyfpdf copied to clipboard
Setting font with write_html
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!
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/
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.
I have the same issue @boludo00 . Can you write some exact instructions here on how to do this? Thanks!
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
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