Combine with mistletoe to use Markdown¶
Several fpdf2
methods allow Markdown syntax elements:
FPDF.cell()
has an optionalmarkdown=True
parameter that makes it possible to use**bold**
,__italics__
or--underlined--
Markdown markersFPDF.multi_cell()
&FPDF.table()
methods have a similar feature
But fpdf2
also allows for basic conversion from HTML to PDF (cf. HTML). This can be combined with the mistletoe library, that follows the CommonMark specification, in order to generate PDF documents from Markdown:
from mistletoe import markdown
html = markdown(
"""
# Top title (ATX)
Subtitle (setext)
-----------------
### An even lower heading (ATX)
**Text in bold**
_Text in italics_
[This is a link](https://github.com/PyFPDF/fpdf2)
<https://py-pdf.github.io/fpdf2/>
This is an unordered list:
* an item
* another item
This is an ordered list:
1. first item
2. second item
3. third item with an unordered sublist:
* an item
* another item
Inline `code span`
A table:
| Foo | Bar | Baz |
| ---:|:---:|:--- |
| Foo | Bar | Baz |
Actual HTML:
<dl>
<dt>Term1</dt><dd>Definition1</dd>
<dt>Term2</dt><dd>Definition2</dd>
</dl>
Some horizontal thematic breaks:
***
---
___
![Alternate description](https://py-pdf.github.io/fpdf2/fpdf2-logo.png)
"""
)
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.write_html(html)
pdf.output("pdf-from-markdown.pdf")
Rendering unicode characters¶
from mistletoe import markdown
html = markdown(
"""
# Unicode:
| Emoji | Description |
| --- | - |
| 😀 | GRINNING FACE |
| 😁 | GRINNING FACE WITH SMILING EYES |
| 😈 | SMILING FACE WITH HORNS |
# A checklist:
* ☐ item 1
* ☑ item 2
* ☐ item 3
"""
)
from fpdf import FPDF
pdf = FPDF()
pdf.add_font("DejaVuSans", fname="test/fonts/DejaVuSans.ttf")
pdf.add_font("DejaVuSans", fname="test/fonts/DejaVuSans-Bold.ttf", style="B")
pdf.set_font("DejaVuSans", size=24)
pdf.add_page()
pdf.write_html(html)
pdf.output("pdf-from-markdown.pdf")
Result: