Repository navigation
|
Hi, I'd like to define document-level styles for various text parts (titles, sub-titles, paragraphs, legends, ...) and use these styles consistently across the document, a bit like CSS classes in HTML. I've seen that a class TextStyle is available to specify everything that I need for that. Is it possible to use such a TextStyle in a context manager to apply a pre-defined style only within it? Something like: with pdf_doc.local_context(textstyle=MyTitle1Style):
pdf_doc.cell("My title")-- edit --- I guess an alternative would be to not use a TextStyle, but to define a doc method, adding the ...
def chapter_title(self, num, label):
with self.local_context():
self.set_font("helvetica", size=12)
self.set_fill_color(200, 220, 255)
self.cell(
0,
6,
f"Chapter {num} : {label}",
new_x="LMARGIN",
new_y="NEXT",
align="L",
fill=True,
)
# Performing a line break:
self.ln(4)Would that be the recommended approach? Any help appreciated! |
Replies: 1 comment 1 reply
|
pdf.write_html(html, tag_styles={
"h1": MyTitle1Style,
"h2": MyTitle2Style,
})For normal from fpdf import TextStyle
TITLE_1 = TextStyle(
font_family="helvetica",
font_style="B",
font_size_pt=18,
color="#203040",
fill_color="#c8dcff",
)
def use_text_style(pdf, style: TextStyle):
return pdf.local_context(
font_family=style.family,
font_style=(
None if style.emphasis is None else style.emphasis.style
),
font_size_pt=style.size_pt,
text_color=style.color,
fill_color=style.fill_color,
)
with use_text_style(pdf_doc, TITLE_1):
pdf_doc.cell(
0, 8, "My title",
fill=True,
new_x="LMARGIN", new_y="NEXT",
)This mapping is necessary because the names on There is one limitation: For that reason, your edited class Report(FPDF):
def chapter_title(self, num, label):
with self.local_context(
font_family="helvetica",
font_style="B",
font_size_pt=12,
fill_color=(200, 220, 255),
):
self.cell(
0, 6, f"Chapter {num}: {label}",
new_x="LMARGIN", new_y="NEXT",
align="L", fill=True,
)
self.ln(4)So: use |
local_context(textstyle=...)is not supported directly.local_context()accepts graphics-state keyword arguments such asfont_family,font_style,font_size_pt,text_color, andfill_color; an unknowntextstyleargument raisesValueError: Unsupported setting(API and accepted settings).TextStyleis mainly used by the HTML/paragraph rendering APIs. For example, it is natively reusable with:For normal
cell()/multi_cell()calls, you can make a small adapter for the font/color subset: