Module fpdf.html
HTML renderer
The contents of this module are internal to fpdf2, and not part of the public API. They may change at any time without prior warning or any deprecation period, in non-backward-compatible ways.
Usage documentation at: https://py-pdf.github.io/fpdf2/HTML.html
Functions
def color_as_decimal(color: str | None = '#000000') ‑> DeviceRGB | DeviceGray | None-
Expand source code Browse git
def color_as_decimal( color: Optional[str] = "#000000", ) -> Optional[DeviceRGB | DeviceGray]: """ Convert a web color name to a (R, G, B) color tuple. cf. https://en.wikipedia.org/wiki/Web_colors#HTML_color_names """ if not color or not color.strip(): return None color = color.strip() # CSS functional notation, as written by many HTML editors: rgb(255, 0, 0) if color.lower().startswith("rgb("): return color_from_rgb_string(color.lower()) # Checks if color is a name and gets the hex value hexcolor = COLOR_DICT.get(color.lower(), color) # Like browsers, a legacy HTML color of six hex digits may omit the "#" if re.fullmatch(r"[0-9a-fA-F]{6}", hexcolor): hexcolor = "#" + hexcolor return color_from_hex_string(hexcolor)Convert a web color name to a (R, G, B) color tuple. cf. https://en.wikipedia.org/wiki/Web_colors#HTML_color_names
def ol_prefix(ol_type: str, index: int) ‑> str | int-
Expand source code Browse git
def ol_prefix(ol_type: str, index: int) -> int | str: if ol_type == "1": return index if ol_type in ("a", "A"): # Like browsers: a..z, then aa, ab..., and plain numbers below 1. if index < 1: return index letters = int_to_letters(index - 1) return letters.lower() if ol_type == "a" else letters if ol_type == "I": return int2roman(index) if ol_type == "i": return int2roman(index).lower() raise NotImplementedError(f"Unsupported type: {ol_type}") def parse_css_style(style_attr: str) ‑> dict[str, str]-
Expand source code Browse git
def parse_css_style(style_attr: str) -> dict[str, str]: """Parse `style="..."` HTML attributes, and return a dict of key-value""" style: dict[str, str] = {} for element in style_attr.split(";"): if not element: continue pair = element.split(":") if len(pair) == 2 and pair[0] and pair[1]: attr, value = pair style[attr.strip()] = value.strip() return styleParse
style="..."HTML attributes, and return a dict of key-value def ul_prefix(ul_type: str, is_ttf_font: bool) ‑> str-
Expand source code Browse git
def ul_prefix(ul_type: str, is_ttf_font: bool) -> str: # Like browsers, the keywords are case-insensitive: type="DISC" is a disc keyword = ul_type.lower() if keyword == "disc": return BULLET_UNICODE if is_ttf_font else MESSAGE_WAITING_WIN1252 if keyword == "circle": return RING_OPERATOR_UNICODE if is_ttf_font else DEGREE_SIGN_WIN1252 if keyword == "square": # Windows-1252 has no square, so core fonts fall back to the bullet return BLACK_SMALL_SQUARE_UNICODE if is_ttf_font else MESSAGE_WAITING_WIN1252 if keyword == "none": # like browsers, list items without a marker, still indented return "" if len(ul_type) == 1: return ul_type raise NotImplementedError(f"Unsupported type: {ul_type}")
Classes
class HTML2FPDF (pdf: FPDF,
image_map: Callable[[str], str] = <function HTML2FPDF.<lambda>>,
li_tag_indent: float | None = None,
dd_tag_indent: float | None = None,
table_line_separators: bool = False,
ul_bullet_char: str = 'disc',
li_prefix_color: int | float | decimal.Decimal | DeviceRGB | DeviceGray | DeviceCMYK | str | Sequence[int | float | decimal.Decimal] = (190, 0, 0),
heading_sizes: dict[str, float] | None = None,
pre_code_font: str | None = None,
warn_on_tags_not_matching: bool = True,
tag_indents: dict[str, float] | None = None,
tag_styles: dict[str, TextStyle] | None = None,
font_family: str = 'times',
render_title_tag: bool = False)-
Expand source code Browse git
class HTML2FPDF(HTMLParser): "Render basic HTML to FPDF" # void elements, which never have an end tag, and elements whose end tag is optional HTML_UNCLOSED_TAGS = ( "area", "base", "br", "col", "dd", "dt", "embed", "hr", "img", "input", "li", "link", "meta", "source", "td", "tr", "track", "wbr", ) TABLE_LINE_HEIGHT = 1.3 def __init__( self, pdf: "FPDF", image_map: Callable[[str], str] = lambda src: src, li_tag_indent: Optional[float] = None, dd_tag_indent: Optional[float] = None, table_line_separators: bool = False, ul_bullet_char: str = "disc", li_prefix_color: ColorInput = (190, 0, 0), heading_sizes: Optional[dict[str, float]] = None, pre_code_font: Optional[str] = None, warn_on_tags_not_matching: bool = True, tag_indents: Optional[dict[str, float]] = None, tag_styles: Optional[dict[str, TextStyle]] = None, font_family: str = "times", render_title_tag: bool = False, ) -> None: """ Args: pdf (fpdf.fpdf.FPDF): an instance of `FPDF` image_map (function): an optional one-argument function that map `<img>` "src" to new image URLs li_tag_indent (int): [**DEPRECATED since v2.7.9**] numeric indentation of `<li>` elements - Set `tag_styles` instead dd_tag_indent (int): [**DEPRECATED since v2.7.9**] numeric indentation of `<dd>` elements - Set `tag_styles` instead table_line_separators (bool): enable horizontal line separators in `<table>`. Defaults to `False`. ul_bullet_char (str): bullet character preceding `<li>` items in `<ul>` lists. You can also specify special bullet names like `"circle"`, `"square"` or `"disc"` (the default). Can also be configured using the HTML `type` attribute of `<ul>` tags. li_prefix_color (tuple, str, fpdf.drawing.DeviceCMYK, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): color for bullets or numbers preceding `<li>` tags. This applies to both `<ul>` & `<ol>` lists. heading_sizes (dict): [**DEPRECATED since v2.7.9**] font size per heading level names ("h1", "h2"...) - Set `tag_styles` instead pre_code_font (str): [**DEPRECATED since v2.7.9**] font to use for `<pre>` & `<code>` blocks - Set `tag_styles` instead warn_on_tags_not_matching (bool): control warnings production for unmatched HTML tags. Defaults to `True`. tag_indents (dict): [**DEPRECATED since v2.8.0**] mapping of HTML tag names to numeric values representing their horizontal left indentation. - Set `tag_styles` instead tag_styles (dict[str, fpdf.fonts.TextStyle]): mapping of HTML tag names to `fpdf.TextStyle` or `fpdf.FontFace` instances font_family (str): optional font family. Default to Times. render_title_tag (bool): Render the document <title> at the beginning of the PDF. Default to False. """ super().__init__() self.pdf = pdf self.ul_bullet_char = ul_bullet_char self.image_map = image_map self.li_prefix_color = ( color_as_decimal(li_prefix_color) if isinstance(li_prefix_color, str) else convert_to_device_color(li_prefix_color) ) self.warn_on_tags_not_matching = warn_on_tags_not_matching # The following 4 attributes are there to serve as "temporary state", # so that changes to those settings are saved, # but not reflected onto self.pdf yet, # and only "effectively" applied when self._write_paragraph() is called. # This way, we often avoid useless operators in the PDF content stream. self.font_family: str = pdf.font_family or font_family self.font_size_pt: float = pdf.font_size_pt self.font_emphasis = TextEmphasis.NONE self.font_color = pdf.text_color # For historical / backward-compatibility reasons, # write_html() sets an active font (Times by default): self.pdf.set_font( family=self.font_family, size=self.font_size_pt, style=self.font_emphasis.style, ) self.style_stack: list[FontFace] = [] # list of FontFace self._page_break_after_paragraph = False self.follows_trailing_space = False # The last write has ended with a space. self.follows_heading = False # We don't want extra space below a heading. self.align: Optional[float | Align] = None self.heading_level: Optional[int] = None self._tags_stack: list[str] = [] self._column = self.pdf.text_columns(skip_leading_spaces=True) self._paragraph: Optional["Paragraph"] = self._column.paragraph() # <pre>-related properties: self._pre_formatted = False # preserve whitespace while True. # nothing written yet to <pre>, remove one initial nl: self._pre_started = False # <a>-related properties: self.href: int | str = "" # <ul>/<ol>-related properties: self.indent = 0 self.line_height_stack: list[float | None] = [] self.ol_type: dict[int, str] = ( {} ) # when inside a <ol> tag, can be "a", "A", "i", "I" or "1" self.bullet: list[int | str] = [] # <title>-related properties: self.render_title_tag = render_title_tag self._in_title = False # id / <a name> targets waiting for the next text to be rendered: self._pending_anchors: list[str] = [] # those of a <table> or its cells, set once the table is rendered: self._table_anchors: list[tuple[str, int]] = [] self._in_style_or_script = False # <table>-related properties: self.table_line_separators = table_line_separators self.table: Optional[Table] = ( None # becomes a Table instance when processing <table> tags ) # the width of each cell of the first row of the current table (None if it has none) self.first_row_widths: list[Optional[tuple[float, bool]]] = [] self.table_row: Optional[Row] = ( None # becomes a Row instance when processing <tr> tags ) self.tr: Optional[dict[str, Optional[str]]] = ( None # becomes a dict of attributes when processing <tr> tags ) self.td_th: Optional[dict[str, Any]] = ( None # becomes a dict of attributes when processing <td>/<th> tags ) # "inserted" is a special attribute indicating that a cell has be inserted in self.table_row self.tag_styles = _scale_units(pdf, DEFAULT_TAG_STYLES) for tag, tag_style in (tag_styles or {}).items(): if tag not in DEFAULT_TAG_STYLES: raise NotImplementedError( f"Cannot set style for HTML tag <{tag}> (contributions are welcome to add support for this)" ) if not isinstance(tag_style, FontFace): raise ValueError( f"tag_styles values must be instances of FontFace or TextStyle - received: {tag_style}" ) # We convert FontFace values provided for block tags into TextStyle values: if tag in BLOCK_TAGS and not isinstance(tag_style, TextStyle): # pylint: disable=redefined-loop-name tag_style = TextStyle( font_family=tag_style.family, font_style=( "" if not tag_style.emphasis else tag_style.emphasis.style ), font_size_pt=tag_style.size_pt, color=tag_style.color, fill_color=tag_style.fill_color, # Using default tag margins: t_margin=self.tag_styles[ tag ].t_margin, # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] l_margin=self.tag_styles[ tag ].l_margin, # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] b_margin=self.tag_styles[ tag ].b_margin, # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] ) self.tag_styles[tag] = tag_style if heading_sizes is not None: warnings.warn( ( "The heading_sizes parameter is deprecated since v2.7.9 " "and will be removed in a future release. " "Set the `tag_styles` parameter instead." ), DeprecationWarning, stacklevel=get_stack_level(), ) for tag, size in heading_sizes.items(): self.tag_styles[tag] = self.tag_styles[tag].replace(font_size_pt=size) if pre_code_font is not None: warnings.warn( ( "The pre_code_font parameter is deprecated since v2.7.9 " "and will be removed in a future release. " "Set the `tag_styles` parameter instead." ), DeprecationWarning, stacklevel=get_stack_level(), ) code_style = self.tag_styles["code"] pre_style = self.tag_styles["pre"] if isinstance(code_style, TextStyle): code_style = code_style.replace(font_family=pre_code_font) else: code_style = code_style.replace(family=pre_code_font) if isinstance(pre_style, TextStyle): pre_style = pre_style.replace(font_family=pre_code_font) else: pre_style = pre_style.replace(family=pre_code_font) self.tag_styles["code"] = code_style self.tag_styles["pre"] = pre_style if dd_tag_indent is not None: warnings.warn( ( "The dd_tag_indent parameter is deprecated since v2.7.9 " "and will be removed in a future release. " "Set the `tag_styles` parameter instead." ), DeprecationWarning, stacklevel=get_stack_level(), ) self.tag_styles["dd"] = self.tag_styles["dd"].replace( l_margin=dd_tag_indent ) if li_tag_indent is not None: warnings.warn( ( "The li_tag_indent parameter is deprecated since v2.7.9 " "and will be removed in a future release. " "Set the `tag_styles` parameter instead." ), DeprecationWarning, stacklevel=get_stack_level(), ) self.tag_styles["li"] = self.tag_styles["li"].replace( l_margin=li_tag_indent ) if tag_indents: warnings.warn( ( "The tag_indents parameter is deprecated since v2.8.0 " "and will be removed in a future release. " "Set the `tag_styles` parameter instead." ), DeprecationWarning, stacklevel=get_stack_level(), ) for tag, indent in tag_indents.items(): if tag not in self.tag_styles: raise NotImplementedError( f"Cannot set style for HTML tag <{tag}> (contributions are welcome to add support for this)" ) self.tag_styles[tag] = self.tag_styles[tag].replace(l_margin=indent) @staticmethod def _normalize_l_margin(l_margin: Any) -> float | Align: if isinstance(l_margin, Align): return l_margin if isinstance(l_margin, (int, float)): return float(l_margin) return 0.0 def _new_paragraph( self, align: Optional[float | Align] = None, line_height: Optional[float] = 1.0, top_margin: float = 0, bottom_margin: float = 0, indent: float | Align = 0, bullet: Optional[str] = None, ) -> None: self._end_paragraph() self.align = align if isinstance(indent, Align): # Explicit alignment takes priority over alignment provided as TextStyle.l_margin: if not self.align: self.align = indent indent = 0 if not top_margin and bullet is None and not self.follows_heading: top_margin = self.font_size_pt / self.pdf.k prev_family = self.pdf.font_family prev_style = self.pdf.font_style prev_size = self.pdf.font_size_pt prev_underline = self.pdf.underline prev_strikethrough = self.pdf.strikethrough prev_current_font = self.pdf.current_font prev_font_set = self.pdf.current_font_is_set_on_page page = self.pdf.page # Set page to 0 to prevent set_font from writing redundant Tf operators to the PDF stream self.pdf.page = 0 self.pdf.set_font( family=self.font_family, style=self.font_emphasis.style, size=self.font_size_pt, ) self.pdf.page = page self._paragraph = self._column.paragraph( text_align=self.align if isinstance(self.align, Align) else None, line_height=line_height, skip_leading_spaces=not self._pre_formatted, top_margin=top_margin, bottom_margin=bottom_margin, indent=indent, bullet_string=bullet or "", ) self._paragraph.anchors.extend(self._pending_anchors) self._pending_anchors.clear() self.pdf.font_family = prev_family self.pdf.font_style = prev_style self.pdf.font_size_pt = prev_size self.pdf.current_font = prev_current_font self.pdf.current_font_is_set_on_page = prev_font_set self.pdf.underline = prev_underline self.pdf.strikethrough = prev_strikethrough self.follows_trailing_space = True self.follows_heading = False def _end_paragraph(self) -> None: self.align = None if not self._paragraph: return paragraph = self._paragraph self._column.end_paragraph() self._column.render() # anchors of text that rendered nothing (e.g. only spaces): current position self._set_anchors(paragraph.unrendered_anchors) self._set_anchors(paragraph.anchors) self._paragraph = None self.follows_trailing_space = True if self._page_break_after_paragraph: # pylint: disable=protected-access self.pdf._perform_page_break() # pyright: ignore[reportPrivateUsage] self._page_break_after_paragraph = False def _take_table_anchors(self) -> None: "Keep the pending anchors of a table with the index of the row they are in." assert self.table is not None # the <table> itself, or a target between rows, belongs to the next row row_index = len(self.table.rows) - (self.table_row is not None) self._table_anchors.extend( (anchor, row_index) for anchor in self._pending_anchors ) self._pending_anchors.clear() def _set_anchors(self, anchors: list[str]) -> None: "Set the anchors that no rendered line has taken at the current position." for anchor in anchors: self.pdf.set_link(name=anchor, y=self.pdf.y) anchors.clear() def _write_paragraph(self, text: str, link: Optional[int | str] = None) -> None: if not text: return if not self._paragraph: self._new_paragraph() # The following local stack is required # in order for FPDF._get_current_graphics_state() # to properly capture the current graphics state, # and then to be able to drop those temporary changes, # because they will only be "effectively" applied in .end_paragraph(). # pylint: disable=protected-access self.pdf._push_local_stack() # pyright: ignore[reportPrivateUsage] prev_page = self.pdf.page self.pdf.page = 0 self.pdf.set_font( family=self.font_family, size=self.font_size_pt, style=self.font_emphasis.style, ) if self.font_color != self.pdf.text_color and self.font_color is not None: self.pdf.set_text_color(self.font_color) assert self._paragraph is not None self._paragraph.anchors.extend(self._pending_anchors) self._pending_anchors.clear() self._paragraph.write(text, link=link) self.pdf.page = prev_page self.pdf._pop_local_stack() # pyright: ignore[reportPrivateUsage] def _ln(self, h: Optional[float] = None) -> None: if self._paragraph: self._paragraph.ln(h=h) else: self._column.ln(h=h) self.follows_trailing_space = True def handle_data(self, data: str) -> None: if self._in_style_or_script: # like browsers, the content of <style> and <script> is never displayed return if self._in_title: if self.pdf.title: LOGGER.warning('Ignoring repeated <title> "%s"', data) else: self.pdf.set_title(data) if not self.render_title_tag: return if self.td_th is not None: data = data.strip() if not data: return if "inserted" in self.td_th: td_th_tag = self.td_th["tag"] raise NotImplementedError( f"Unsupported nested HTML tags inside <{td_th_tag}> element: <{self._tags_stack[-1]}>" ) # We could potentially support nested <b> / <em> / <font> tags # by building a list of Fragment instances from the HTML cell content # and then passing those fragments to Row.cell(). # However there should be an incoming refactoring of this code # dedicated to text layout, and we should probably wait for that # before supporting this feature. align = self.td_th.get("align") if align is None and self.tr is not None: align = self.tr.get("align") if align: try: align = Align.coerce(align) except ValueError: # like browsers, and like <p>, ignore a value such as "middle", # keeping the default: <th> cells are centered align = Align.C if self.td_th.get("tag") == "th" else None bgcolor_str = _without_transparent(self.td_th.get("bgcolor")) if bgcolor_str is None and self.tr is not None: bgcolor_str = _without_transparent(self.tr.get("bgcolor")) bgcolor = color_as_decimal(bgcolor_str) colspan = _parse_html_span(self.td_th.get("colspan")) rowspan = _parse_html_span(self.td_th.get("rowspan")) emphasis = 0 if self.td_th.get("b"): emphasis |= TextEmphasis.B if self.td_th.get("i"): emphasis |= TextEmphasis.I if self.td_th.get("U"): emphasis |= TextEmphasis.U font_family = ( self.font_family if self.font_family != self.pdf.font_family else None ) font_size_pt = ( self.font_size_pt if self.font_size_pt != self.pdf.font_size_pt else None ) font_style = None if font_family or emphasis or font_size_pt or bgcolor: font_style = FontFace( family=font_family, emphasis=emphasis, size_pt=font_size_pt, color=self.pdf.text_color, fill_color=bgcolor, ) assert self.table_row is not None self.table_row.cell( text=data, align=align, style=font_style, colspan=colspan, rowspan=rowspan, ) self.td_th["inserted"] = True elif self.table is not None: # ignore anything else than td inside a table pass elif self._pre_formatted: # pre blocks # If we want to mimic the exact HTML semantics about newlines at the # beginning and end of the block, then this needs some more thought. if data.startswith("\n") and self._pre_started: if data.endswith("\n"): data = data[1:-1] else: data = data[1:] self._pre_started = False self._write_data(data) else: data = _WS_SUB_PAT.sub(" ", data) if self.follows_trailing_space and data[0] == " ": self._write_data(data[1:]) else: self._write_data(data) self.follows_trailing_space = data[-1] == " " if self._page_break_after_paragraph: self._end_paragraph() def _write_data(self, data: str) -> None: if self.href: self.put_link(data) else: if self.heading_level: if self.pdf.section_title_styles: raise NotImplementedError( "Combining write_html() & section styles is currently not supported." " You can open up an issue on github.com/py-pdf/fpdf2 if this is something you would like to see implemented." ) self.pdf.start_section(data, self.heading_level - 1, strict=False) self._write_paragraph(data) def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: self._pre_started = False attrs_dict: dict[str, str | None] = dict(attrs) del attrs css_style = parse_css_style(attrs_dict.get("style") or "") self._tags_stack.append(tag) # like browsers, an id and the name of an <a> are targets for href="#..." links; # the destination is set where the target is rendered (see _write_paragraph) for anchor in ( attrs_dict.get("id"), attrs_dict.get("name") if tag == "a" else None, ): if ( anchor and anchor.strip() and anchor.strip() not in self._pending_anchors ): self._pending_anchors.append(anchor.strip()) if css_style.get("break-before") == "page": self._end_paragraph() # pylint: disable=protected-access self.pdf._perform_page_break() # pyright: ignore[reportPrivateUsage] if tag in ("b", "i", "u") and self.td_th is not None: self.td_th[tag] = True if tag == "a": # <a name="..."> and <a id="..."> are anchors, not links: no href means plain text self.href = attrs_dict.get("href") or "" try: page = int(self.href) self.href = self.pdf.add_link(page=page) except ValueError: pass if tag == "br": self._write_paragraph("\n") if tag == "hr": self._end_paragraph() width_str = css_style.get("width", attrs_dict.get("width")) if width_str: width_str = width_str.strip() if width_str.endswith("%"): hr_width = self.pdf.epw * _parse_html_percentage(width_str) / 100 else: hr_width = _parse_html_dimension(width_str) / self.pdf.k else: hr_width = self.pdf.epw # Centering: x_start = self.pdf.l_margin + (self.pdf.epw - hr_width) / 2 self.pdf.line( x1=x_start, y1=self.pdf.y, x2=x_start + hr_width, y2=self.pdf.y, ) self._write_paragraph("\n") if tag == "p": self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) align: Optional[Align] = None if "align" in attrs_dict: try: align_str = attrs_dict.get("align") align = Align.coerce(align_str) if align_str is not None else None except ValueError: align = None line_height_str = css_style.get( "line-height", attrs_dict.get("line-height") ) # "line-height" attributes are not valid in HTML, # but we support it for backward compatibility, # because fpdf2 honors it since 2.6.1 and PR #629 # YYY parse and convert non-float line_height values line_height = _parse_line_height(line_height_str) tag_style = self.tag_styles[tag] if tag_style.color is not None and tag_style.color != self.font_color: self.font_color = tag_style.color if tag_style.family is not None and tag_style.family != self.font_family: self.font_family = tag_style.family if tag_style.size_pt is not None and tag_style.size_pt != self.font_size_pt: self.font_size_pt = tag_style.size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( align=align, line_height=line_height or 1.0, top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) if tag in HEADING_TAGS: self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) self.heading_level = 0 if tag == "title" else int(tag[1:]) tag_style = self.tag_styles[tag] hsize = (tag_style.size_pt or self.font_size_pt) / self.pdf.k align = None if "align" in attrs_dict: try: align_str = attrs_dict.get("align") align = Align.coerce(align_str) if align_str is not None else None except ValueError: align = None if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( align=align, top_margin=t_margin, bottom_margin=b_margin * hsize, indent=l_margin, ) css_color = _css_color(css_style.get("color")) if css_color is not None: self.font_color = css_color elif _without_transparent(attrs_dict.get("color")) is not None: # "color" attributes are not valid in HTML, # but we support it for backward compatibility: self.font_color = color_as_decimal(attrs_dict["color"]) elif tag_style.color is not None and tag_style.color != self.font_color: self.font_color = tag_style.color if tag_style.family is not None and tag_style.family != self.font_family: self.font_family = tag_style.family if tag_style.size_pt is not None and tag_style.size_pt != self.font_size_pt: self.font_size_pt = tag_style.size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis if tag in ( "b", "blockquote", "center", "code", "del", "em", "i", "dd", "dt", "pre", "s", "strong", "u", ): if tag in BLOCK_TAGS: self._end_paragraph() self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) tag_style = self.tag_styles[tag] if tag_style.color: self.font_color = tag_style.color self.font_family = tag_style.family or self.font_family self.font_size_pt = tag_style.size_pt or self.font_size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis if tag == "pre": self._pre_formatted = True self._pre_started = True if tag in BLOCK_TAGS: if tag == "dd": # Not compliant with the HTML spec, but backward-compatible # cf. https://github.com/py-pdf/fpdf2/pull/1217#discussion_r1666643777 self.follows_heading = True if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( line_height=( self.line_height_stack[-1] if self.line_height_stack else None ), top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) if tag == "ul": self.indent += 1 bullet_char = attrs_dict.get("type") or self.ul_bullet_char # like browsers, an unknown type keeps the default marker; # a single character is still used as the bullet itself if len(bullet_char) > 1 and bullet_char.lower() not in ( "disc", "circle", "square", "none", ): bullet_char = self.ul_bullet_char self.bullet.append(bullet_char) line_height_str = css_style.get( "line-height", attrs_dict.get("line-height") ) # "line-height" attributes are not valid in HTML, # but we support it for backward compatibility, # because fpdf2 honors it since 2.6.1 and PR #629 # YYY parse and convert non-float line_height values # Invalid line-height: ignored, the default value is used line_height = _parse_line_height(line_height_str) self.line_height_stack.append(line_height) if self.indent == 1: tag_style = self.tag_styles[tag] if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( line_height=0, top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) self._write_paragraph("\u00a0") self._end_paragraph() if tag == "ol": self.indent += 1 start = 1 if "start" in attrs_dict: start_str = attrs_dict["start"] or "1" try: start = int(start_str) except ValueError: start = 1 self.bullet.append(start - 1) ol_type = attrs_dict.get("type") or "1" # like browsers, an unknown type (they are case-sensitive) gives numbers self.ol_type[self.indent] = ( ol_type if ol_type in ("1", "a", "A", "i", "I") else "1" ) line_height_str = css_style.get("line-height") or attrs_dict.get( "line-height" ) # "line-height" attributes are not valid in HTML, # but we support it for backward compatibility, # because fpdf2 honors it since 2.6.1 and PR #629 # YYY parse and convert non-float line_height values # Invalid line-height: ignored, the default value is used line_height = _parse_line_height(line_height_str) self.line_height_stack.append(line_height) if self.indent == 1: tag_style = self.tag_styles[tag] if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( line_height=0, top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) self._write_paragraph("\u00a0") self._end_paragraph() if tag == "li": prev_text_color = self.pdf.text_color self.pdf.text_color = self.li_prefix_color if self.bullet: bullet = self.bullet[self.indent - 1] else: # Allow <li> to be used outside of <ul> or <ol>. bullet = self.ul_bullet_char if not isinstance(bullet, int): bullet = ul_prefix(bullet, self.pdf.is_ttf_font) if not isinstance(bullet, str): bullet += 1 # like browsers, <li value="N"> numbers this item N and the next ones from there try: bullet = int((attrs_dict.get("value") or "").strip()) except ValueError: pass self.bullet[self.indent - 1] = bullet ol_type = self.ol_type[self.indent] bullet = f"{ol_prefix(ol_type, bullet)}." tag_style = self.tag_styles[tag] if isinstance(tag_style, TextStyle): b_margin = tag_style.b_margin l_margin = tag_style.l_margin t_margin = tag_style.t_margin else: b_margin = l_margin = t_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) numeric_indent = 0.0 if isinstance(l_margin, Align) else l_margin self._new_paragraph( line_height=( self.line_height_stack[-1] if self.line_height_stack else None ), indent=numeric_indent * self.indent, top_margin=t_margin, bottom_margin=b_margin, bullet=bullet, ) self.pdf.text_color = prev_text_color if tag == "font": self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) if _without_transparent(attrs_dict.get("color")) is not None: self.font_color = color_as_decimal(attrs_dict["color"]) if "font-size" in css_style: font_size_str = css_style.get("font-size") or "" try: # like browsers, a CSS length such as "14pt" or "12px"; # a number without a unit is still read as points font_size = resolve_length(font_size_str) # like browsers, a negative or infinite font size is ignored if math.isfinite(font_size) and font_size >= 0: self.font_size_pt = font_size except ValueError: pass elif "size" in attrs_dict: font_size_str = attrs_dict.get("size") or "" try: font_size = float(font_size_str) if math.isfinite(font_size) and font_size >= 0: self.font_size_pt = font_size except ValueError: pass if "face" in attrs_dict: face = attrs_dict.get("face") or "" # pylint: disable=protected-access catalog = ( self.pdf._resource_catalog # pyright: ignore[reportPrivateUsage] ) # bold and italic select the font file; underline and strikethrough do not style = "".join(c for c in self.font_emphasis.style if c in "BI") try: # like browsers, the first available font of a list such as # "Arial, Helvetica, sans-serif"; set_font() then adds it, # with its checks (such as PDF/A requiring embedded fonts) self.font_family = catalog.resolve_font_family(face, style) except KeyError: # no font of the list is available: set_font() reports it, as before self.font_family = face.lower() if tag == "table": if self.table is not None: parent = self.td_th["tag"] if self.td_th is not None else "table" raise NotImplementedError( f"Unsupported nested HTML tags inside <{parent}> element: <table>" ) self._end_paragraph() width: Optional[float] = None width_str = css_style.get("width") or attrs_dict.get("width") if width_str: width_str = width_str.strip() if width_str.endswith("%"): width = self.pdf.epw * _parse_html_percentage(width_str) / 100 else: width = _parse_html_dimension(width_str) / self.pdf.k if width <= 0: # like browsers, an invalid width is ignored width = None elif width > self.pdf.epw: LOGGER.warning( 'Table width="%s" is wider than the page: using the page width', width_str, ) width = self.pdf.epw if "border" not in attrs_dict: # default borders borders_layout = ( "HORIZONTAL_LINES" if self.table_line_separators else "SINGLE_TOP_LINE" ) else: borders_str = attrs_dict["border"] or "" try: if int(borders_str) > 0: # explicitly enabled borders borders_layout = ( "ALL" if self.table_line_separators else "NO_HORIZONTAL_LINES" ) else: # explicitly disabled borders borders_layout = "NONE" except ValueError: borders_layout = "NONE" align = Align.coerce(attrs_dict.get("align") or "CENTER") padding = None if "cellpadding" in attrs_dict: pad_val = attrs_dict["cellpadding"] match = unit_splitter.match((pad_val or "").strip()) if match and not match.group("unit"): try: padding = float(match.group("value")) except ValueError: padding = 0.0 else: padding = _parse_html_dimension(pad_val) / self.pdf.k sp_val = attrs_dict.get("cellspacing") if sp_val is not None: match = unit_splitter.match((sp_val or "").strip()) if match and not match.group("unit"): try: spacing = float(match.group("value")) except ValueError: spacing = 0.0 else: spacing = _parse_html_dimension(sp_val) / self.pdf.k if spacing < 0: # An invalid (negative) cellspacing is ignored, like browsers do spacing = 0.0 else: spacing = 0.0 self.first_row_widths = [] self.table = Table( self.pdf, align=align, borders_layout=borders_layout, line_height=self.font_size_pt / self.pdf.k * self.TABLE_LINE_HEIGHT, width=width, padding=padding, gutter_width=spacing, gutter_height=spacing, ) self._ln() if tag == "tr": if not self.table: raise FPDFException("Invalid HTML: <tr> used outside any <table>") self.tr = {k.lower(): v for k, v in attrs_dict.items()} self.table_row = self.table.row() if tag in ("td", "th"): if not self.table or not self.table_row: raise FPDFException(f"Invalid HTML: <{tag}> used outside any <tr>") self.td_th = {k.lower(): v for k, v in attrs_dict.items()} self.td_th["tag"] = tag if tag == "th": if "align" not in self.td_th: self.td_th["align"] = "CENTER" self.td_th["b"] = True elif len(self.table.rows) == 1 and not self.table_row.cells: # => we are in the 1st <tr>, and the 1st cell is a <td> # => we do not treat the first row as a header # pylint: disable=protected-access self.table._first_row_as_headings = ( False # pyright: ignore[reportPrivateUsage] ) self.table._num_heading_rows = 0 # pyright: ignore[reportPrivateUsage] if "height" in attrs_dict: LOGGER.warning( 'Ignoring unsupported height="%s" specified on a <%s>', attrs_dict["height"], tag, ) cell_width: Optional[tuple[float, bool]] = None if "width" in attrs_dict: width_str = (attrs_dict["width"] or "0").strip() if len(self.table.rows) == 1: # => first table row if width_str.endswith("%"): cell_width = (_parse_html_percentage(width_str), True) else: cell_width = (_parse_html_dimension(width_str), False) else: LOGGER.warning( 'Ignoring width="%s" specified on a <%s> that is not in the first <tr>', width_str, tag, ) if len(self.table.rows) == 1: # a cell that spans several columns gives each of them an equal part span = _parse_html_span(attrs_dict.get("colspan")) if cell_width is None: self.first_row_widths.extend([None] * span) else: self.first_row_widths.extend( [(cell_width[0] / span, cell_width[1])] * span ) if cell_width is not None: # pylint: disable=protected-access self.table._col_widths = [ w[0] for w in self.first_row_widths if w is not None ] if tag == "img" and "src" in attrs_dict: width = _parse_html_dimension(attrs_dict.get("width")) / self.pdf.k height = _parse_html_dimension(attrs_dict.get("height")) / self.pdf.k if self.table_row: # => <img> in a <table> if width or height: LOGGER.warning( 'Ignoring unsupported "width" / "height" set on <img> element' ) if self.align: LOGGER.warning("Ignoring unsupported <img> alignment") self.table_row.cell(img=attrs_dict["src"], img_fill_width=True) assert self.td_th is not None self.td_th["inserted"] = True self._take_table_anchors() return x: float | Align = self.pdf.get_x() if self.align: x = self.align info = self.pdf.image( self.image_map(attrs_dict["src"] or ""), x=x, w=width, h=height, link=self.href, ) # targets point to the top of the image, after any page break it caused for anchor in self._pending_anchors: self.pdf.set_link(name=anchor, y=self.pdf.y - info.rendered_height) self._pending_anchors.clear() if tag == "toc": self._end_paragraph() self.pdf.set_font( family=self.font_family, size=self.font_size_pt, style=self.font_emphasis.style, ) if self.font_color != self.pdf.text_color and self.font_color is not None: self.pdf.set_text_color(self.font_color) self.pdf.insert_toc_placeholder( self.render_toc, pages=int(attrs_dict.get("pages") or "1") ) if tag == "table" or self.table is not None: # table cells are not rendered as paragraphs: the row position is used self._take_table_anchors() if tag == "sup": self.pdf.char_vpos = CharVPos.SUP if tag == "sub": self.pdf.char_vpos = CharVPos.SUB if tag == "title": self._in_title = True if tag in ("style", "script"): self._in_style_or_script = True if css_style.get("break-after") == "page": if tag in ("br", "hr", "img"): self._end_paragraph() # pylint: disable=protected-access self.pdf._perform_page_break() # pyright: ignore[reportPrivateUsage] else: self._page_break_after_paragraph = True def handle_endtag(self, tag: str) -> None: while ( self._tags_stack and tag != self._tags_stack[-1] and self._tags_stack[-1] in self.HTML_UNCLOSED_TAGS ): self._tags_stack.pop() if not self._tags_stack: if self.warn_on_tags_not_matching: LOGGER.warning( "Unexpected HTML end tag </%s>, start tag may be missing?", tag ) elif tag == self._tags_stack[-1]: self._tags_stack.pop() elif self.warn_on_tags_not_matching: LOGGER.warning( "Unexpected HTML end tag </%s>, start tag was <%s>", tag, self._tags_stack[-1], ) if tag == "a": self.href = "" if tag == "p": if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color self._end_paragraph() self.align = None if tag in HEADING_TAGS: self.heading_level = None if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color self._end_paragraph() self.follows_heading = True # We don't want extra space below a heading. if tag in ( "b", "blockquote", "center", "code", "em", "i", "dd", "dt", "pre", "s", "strong", "u", ): if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color if tag == "pre": self._pre_formatted = False self._pre_started = False if tag in BLOCK_TAGS: self._end_paragraph() if tag in ("ul", "ol"): self._end_paragraph() if tag == "ol": self.ol_type.pop(self.indent) self.indent -= 1 self.line_height_stack.pop() self.bullet.pop() if tag == "table": assert self.table is not None # like browsers, a rowspan that goes past the last row stops at the last row rows = self.table.rows for i, row in enumerate(rows): for j, cell in enumerate(row.cells): if isinstance(cell, Cell) and cell.rowspan > len(rows) - i: row.cells[j] = replace(cell, rowspan=len(rows) - i) if None in self.first_row_widths and any(self.first_row_widths): # some cells of the first row have no width: they share the rest # pylint: disable=protected-access table_width = float(self.table._width or self.pdf.epw) usable_width = ( table_width - (len(self.first_row_widths) - 1) * self.table._gutter_width - 2 * float(self.table._outer_border_margin[0]) ) self.table._col_widths = _fill_missing_widths( self.first_row_widths, table_width * self.pdf.k, usable_width * self.pdf.k, ) self.table.render() # table targets: where their row was rendered, after any page break positions = self.table.row_positions or [(self.pdf.page, self.pdf.y)] for anchor, row_index in self._table_anchors: page, y = positions[min(row_index, len(positions) - 1)] self.pdf.set_link(name=anchor, y=y, page=page) self._table_anchors.clear() self.table = None self._ln() if tag == "tr": self.tr = None self.table_row = None if tag in ("td", "th"): assert ( self.td_th is not None and self.tr is not None and self.table_row is not None ) if "inserted" not in self.td_th: # handle_data() was not called => we call it to produce an empty cell: bgcolor = color_as_decimal( _without_transparent(self.td_th.get("bgcolor")) or _without_transparent(self.tr.get("bgcolor", None)) ) style = FontFace(fill_color=bgcolor) if bgcolor else None colspan = _parse_html_span(self.td_th.get("colspan")) rowspan = _parse_html_span(self.td_th.get("rowspan")) self.table_row.cell( text="", style=style, colspan=colspan, rowspan=rowspan ) self.td_th = None if tag == "font": if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color if tag == "sup": self.pdf.char_vpos = CharVPos.LINE if tag == "sub": self.pdf.char_vpos = CharVPos.LINE if tag == "title": self._in_title = False if tag in ("style", "script"): self._in_style_or_script = False def feed(self, data: str) -> None: super().feed(data) while self._tags_stack and self._tags_stack[-1] in self.HTML_UNCLOSED_TAGS: self._tags_stack.pop() self._end_paragraph() # render the final chunk of text and clean up our local context. self._set_anchors(self._pending_anchors) if self._tags_stack and self.warn_on_tags_not_matching: LOGGER.warning("Missing HTML end tag for <%s>", self._tags_stack[-1]) def put_link(self, text: str) -> None: "Insert a hyperlink" prev_style = FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) tag_style = self.tag_styles["a"] if tag_style.color: self.font_color = tag_style.color self.font_family = tag_style.family or self.font_family self.font_size_pt = tag_style.size_pt or self.font_size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis self._write_paragraph(text, link=self.href) # Restore previous style: self.font_family = prev_style.family or self.font_family self.font_size_pt = prev_style.size_pt or self.font_size_pt self.font_emphasis = prev_style.emphasis or TextEmphasis.NONE self.font_color = prev_style.color # pylint: disable=no-self-use def render_toc(self, pdf: "FPDF", outline: list[OutlineSection]) -> None: "This method can be overridden by subclasses to customize the Table of Contents style." pdf.ln() for section in outline: link = pdf.add_link(page=section.page_number) text = f"{' ' * section.level * 2} {section.name}" text += f" {'.' * (60 - section.level * 2 - len(section.name))} {section.page_number}" pdf.multi_cell( w=pdf.epw, h=pdf.font_size, text=text, new_x=XPos.LMARGIN, new_y=YPos.NEXT, link=link, ) # Subclasses of _markupbase.ParserBase must implement this: def error(self, message: str) -> None: raise RuntimeError(message)Render basic HTML to FPDF
- Args
- -----=
pdf:FPDF- an instance of
FPDF image_map:function- an optional one-argument function that map
<img>"src" to new image URLs li_tag_indent:int- [DEPRECATED since v2.7.9]
numeric indentation of
<li>elements - Settag_stylesinstead dd_tag_indent:int- [DEPRECATED since v2.7.9]
numeric indentation of
<dd>elements - Settag_stylesinstead table_line_separators:bool- enable horizontal line separators in
<table>. Defaults toFalse. ul_bullet_char:str- bullet character preceding
<li>items in<ul>lists. You can also specify special bullet names like"circle","square"or"disc"(the default). Can also be configured using the HTMLtypeattribute of<ul>tags. li_prefix_color:tuple, str, fpdf.drawing.DeviceCMYK, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB- color for bullets
or numbers preceding
<li>tags. This applies to both<ul>&<ol>lists. heading_sizes:dict- [DEPRECATED since v2.7.9]
font size per heading level names ("h1", "h2"…) - Set
tag_stylesinstead pre_code_font:str- [DEPRECATED since v2.7.9]
font to use for
<pre>&<code>blocks - Settag_stylesinstead warn_on_tags_not_matching:bool- control warnings production for unmatched HTML tags. Defaults to
True. tag_indents:dict- [DEPRECATED since v2.8.0]
mapping of HTML tag names to numeric values representing their horizontal left indentation. - Set
tag_stylesinstead tag_styles:dict[str, TextStyle]- mapping of HTML tag names to
fpdf.TextStyleorfpdf.FontFaceinstances font_family:str- optional font family. Default to Times.
render_title_tag:bool- Render the document
at the beginning of the PDF. Default to False.
Ancestors
- html.parser.HTMLParser
- _markupbase.ParserBase
Class variables
var HTML_UNCLOSED_TAGS-
The type of the None singleton.
var TABLE_LINE_HEIGHT-
The type of the None singleton.
Methods
def error(self, message: str) ‑> None-
Expand source code Browse git
def error(self, message: str) -> None: raise RuntimeError(message) def feed(self, data: str) ‑> None-
Expand source code Browse git
def feed(self, data: str) -> None: super().feed(data) while self._tags_stack and self._tags_stack[-1] in self.HTML_UNCLOSED_TAGS: self._tags_stack.pop() self._end_paragraph() # render the final chunk of text and clean up our local context. self._set_anchors(self._pending_anchors) if self._tags_stack and self.warn_on_tags_not_matching: LOGGER.warning("Missing HTML end tag for <%s>", self._tags_stack[-1])Feed data to the parser.
Call this as often as you want, with as little or as much text as you want (may include '\n').
def handle_data(self, data: str) ‑> None-
Expand source code Browse git
def handle_data(self, data: str) -> None: if self._in_style_or_script: # like browsers, the content of <style> and <script> is never displayed return if self._in_title: if self.pdf.title: LOGGER.warning('Ignoring repeated <title> "%s"', data) else: self.pdf.set_title(data) if not self.render_title_tag: return if self.td_th is not None: data = data.strip() if not data: return if "inserted" in self.td_th: td_th_tag = self.td_th["tag"] raise NotImplementedError( f"Unsupported nested HTML tags inside <{td_th_tag}> element: <{self._tags_stack[-1]}>" ) # We could potentially support nested <b> / <em> / <font> tags # by building a list of Fragment instances from the HTML cell content # and then passing those fragments to Row.cell(). # However there should be an incoming refactoring of this code # dedicated to text layout, and we should probably wait for that # before supporting this feature. align = self.td_th.get("align") if align is None and self.tr is not None: align = self.tr.get("align") if align: try: align = Align.coerce(align) except ValueError: # like browsers, and like <p>, ignore a value such as "middle", # keeping the default: <th> cells are centered align = Align.C if self.td_th.get("tag") == "th" else None bgcolor_str = _without_transparent(self.td_th.get("bgcolor")) if bgcolor_str is None and self.tr is not None: bgcolor_str = _without_transparent(self.tr.get("bgcolor")) bgcolor = color_as_decimal(bgcolor_str) colspan = _parse_html_span(self.td_th.get("colspan")) rowspan = _parse_html_span(self.td_th.get("rowspan")) emphasis = 0 if self.td_th.get("b"): emphasis |= TextEmphasis.B if self.td_th.get("i"): emphasis |= TextEmphasis.I if self.td_th.get("U"): emphasis |= TextEmphasis.U font_family = ( self.font_family if self.font_family != self.pdf.font_family else None ) font_size_pt = ( self.font_size_pt if self.font_size_pt != self.pdf.font_size_pt else None ) font_style = None if font_family or emphasis or font_size_pt or bgcolor: font_style = FontFace( family=font_family, emphasis=emphasis, size_pt=font_size_pt, color=self.pdf.text_color, fill_color=bgcolor, ) assert self.table_row is not None self.table_row.cell( text=data, align=align, style=font_style, colspan=colspan, rowspan=rowspan, ) self.td_th["inserted"] = True elif self.table is not None: # ignore anything else than td inside a table pass elif self._pre_formatted: # pre blocks # If we want to mimic the exact HTML semantics about newlines at the # beginning and end of the block, then this needs some more thought. if data.startswith("\n") and self._pre_started: if data.endswith("\n"): data = data[1:-1] else: data = data[1:] self._pre_started = False self._write_data(data) else: data = _WS_SUB_PAT.sub(" ", data) if self.follows_trailing_space and data[0] == " ": self._write_data(data[1:]) else: self._write_data(data) self.follows_trailing_space = data[-1] == " " if self._page_break_after_paragraph: self._end_paragraph() def handle_endtag(self, tag: str) ‑> None-
Expand source code Browse git
def handle_endtag(self, tag: str) -> None: while ( self._tags_stack and tag != self._tags_stack[-1] and self._tags_stack[-1] in self.HTML_UNCLOSED_TAGS ): self._tags_stack.pop() if not self._tags_stack: if self.warn_on_tags_not_matching: LOGGER.warning( "Unexpected HTML end tag </%s>, start tag may be missing?", tag ) elif tag == self._tags_stack[-1]: self._tags_stack.pop() elif self.warn_on_tags_not_matching: LOGGER.warning( "Unexpected HTML end tag </%s>, start tag was <%s>", tag, self._tags_stack[-1], ) if tag == "a": self.href = "" if tag == "p": if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color self._end_paragraph() self.align = None if tag in HEADING_TAGS: self.heading_level = None if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color self._end_paragraph() self.follows_heading = True # We don't want extra space below a heading. if tag in ( "b", "blockquote", "center", "code", "em", "i", "dd", "dt", "pre", "s", "strong", "u", ): if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color if tag == "pre": self._pre_formatted = False self._pre_started = False if tag in BLOCK_TAGS: self._end_paragraph() if tag in ("ul", "ol"): self._end_paragraph() if tag == "ol": self.ol_type.pop(self.indent) self.indent -= 1 self.line_height_stack.pop() self.bullet.pop() if tag == "table": assert self.table is not None # like browsers, a rowspan that goes past the last row stops at the last row rows = self.table.rows for i, row in enumerate(rows): for j, cell in enumerate(row.cells): if isinstance(cell, Cell) and cell.rowspan > len(rows) - i: row.cells[j] = replace(cell, rowspan=len(rows) - i) if None in self.first_row_widths and any(self.first_row_widths): # some cells of the first row have no width: they share the rest # pylint: disable=protected-access table_width = float(self.table._width or self.pdf.epw) usable_width = ( table_width - (len(self.first_row_widths) - 1) * self.table._gutter_width - 2 * float(self.table._outer_border_margin[0]) ) self.table._col_widths = _fill_missing_widths( self.first_row_widths, table_width * self.pdf.k, usable_width * self.pdf.k, ) self.table.render() # table targets: where their row was rendered, after any page break positions = self.table.row_positions or [(self.pdf.page, self.pdf.y)] for anchor, row_index in self._table_anchors: page, y = positions[min(row_index, len(positions) - 1)] self.pdf.set_link(name=anchor, y=y, page=page) self._table_anchors.clear() self.table = None self._ln() if tag == "tr": self.tr = None self.table_row = None if tag in ("td", "th"): assert ( self.td_th is not None and self.tr is not None and self.table_row is not None ) if "inserted" not in self.td_th: # handle_data() was not called => we call it to produce an empty cell: bgcolor = color_as_decimal( _without_transparent(self.td_th.get("bgcolor")) or _without_transparent(self.tr.get("bgcolor", None)) ) style = FontFace(fill_color=bgcolor) if bgcolor else None colspan = _parse_html_span(self.td_th.get("colspan")) rowspan = _parse_html_span(self.td_th.get("rowspan")) self.table_row.cell( text="", style=style, colspan=colspan, rowspan=rowspan ) self.td_th = None if tag == "font": if self.style_stack: font_face = self.style_stack.pop() self.font_family = font_face.family or self.font_family self.font_size_pt = font_face.size_pt or self.font_size_pt self.font_emphasis = font_face.emphasis or TextEmphasis.NONE self.font_color = font_face.color if tag == "sup": self.pdf.char_vpos = CharVPos.LINE if tag == "sub": self.pdf.char_vpos = CharVPos.LINE if tag == "title": self._in_title = False if tag in ("style", "script"): self._in_style_or_script = False def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) ‑> None-
Expand source code Browse git
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: self._pre_started = False attrs_dict: dict[str, str | None] = dict(attrs) del attrs css_style = parse_css_style(attrs_dict.get("style") or "") self._tags_stack.append(tag) # like browsers, an id and the name of an <a> are targets for href="#..." links; # the destination is set where the target is rendered (see _write_paragraph) for anchor in ( attrs_dict.get("id"), attrs_dict.get("name") if tag == "a" else None, ): if ( anchor and anchor.strip() and anchor.strip() not in self._pending_anchors ): self._pending_anchors.append(anchor.strip()) if css_style.get("break-before") == "page": self._end_paragraph() # pylint: disable=protected-access self.pdf._perform_page_break() # pyright: ignore[reportPrivateUsage] if tag in ("b", "i", "u") and self.td_th is not None: self.td_th[tag] = True if tag == "a": # <a name="..."> and <a id="..."> are anchors, not links: no href means plain text self.href = attrs_dict.get("href") or "" try: page = int(self.href) self.href = self.pdf.add_link(page=page) except ValueError: pass if tag == "br": self._write_paragraph("\n") if tag == "hr": self._end_paragraph() width_str = css_style.get("width", attrs_dict.get("width")) if width_str: width_str = width_str.strip() if width_str.endswith("%"): hr_width = self.pdf.epw * _parse_html_percentage(width_str) / 100 else: hr_width = _parse_html_dimension(width_str) / self.pdf.k else: hr_width = self.pdf.epw # Centering: x_start = self.pdf.l_margin + (self.pdf.epw - hr_width) / 2 self.pdf.line( x1=x_start, y1=self.pdf.y, x2=x_start + hr_width, y2=self.pdf.y, ) self._write_paragraph("\n") if tag == "p": self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) align: Optional[Align] = None if "align" in attrs_dict: try: align_str = attrs_dict.get("align") align = Align.coerce(align_str) if align_str is not None else None except ValueError: align = None line_height_str = css_style.get( "line-height", attrs_dict.get("line-height") ) # "line-height" attributes are not valid in HTML, # but we support it for backward compatibility, # because fpdf2 honors it since 2.6.1 and PR #629 # YYY parse and convert non-float line_height values line_height = _parse_line_height(line_height_str) tag_style = self.tag_styles[tag] if tag_style.color is not None and tag_style.color != self.font_color: self.font_color = tag_style.color if tag_style.family is not None and tag_style.family != self.font_family: self.font_family = tag_style.family if tag_style.size_pt is not None and tag_style.size_pt != self.font_size_pt: self.font_size_pt = tag_style.size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( align=align, line_height=line_height or 1.0, top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) if tag in HEADING_TAGS: self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) self.heading_level = 0 if tag == "title" else int(tag[1:]) tag_style = self.tag_styles[tag] hsize = (tag_style.size_pt or self.font_size_pt) / self.pdf.k align = None if "align" in attrs_dict: try: align_str = attrs_dict.get("align") align = Align.coerce(align_str) if align_str is not None else None except ValueError: align = None if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( align=align, top_margin=t_margin, bottom_margin=b_margin * hsize, indent=l_margin, ) css_color = _css_color(css_style.get("color")) if css_color is not None: self.font_color = css_color elif _without_transparent(attrs_dict.get("color")) is not None: # "color" attributes are not valid in HTML, # but we support it for backward compatibility: self.font_color = color_as_decimal(attrs_dict["color"]) elif tag_style.color is not None and tag_style.color != self.font_color: self.font_color = tag_style.color if tag_style.family is not None and tag_style.family != self.font_family: self.font_family = tag_style.family if tag_style.size_pt is not None and tag_style.size_pt != self.font_size_pt: self.font_size_pt = tag_style.size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis if tag in ( "b", "blockquote", "center", "code", "del", "em", "i", "dd", "dt", "pre", "s", "strong", "u", ): if tag in BLOCK_TAGS: self._end_paragraph() self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) tag_style = self.tag_styles[tag] if tag_style.color: self.font_color = tag_style.color self.font_family = tag_style.family or self.font_family self.font_size_pt = tag_style.size_pt or self.font_size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis if tag == "pre": self._pre_formatted = True self._pre_started = True if tag in BLOCK_TAGS: if tag == "dd": # Not compliant with the HTML spec, but backward-compatible # cf. https://github.com/py-pdf/fpdf2/pull/1217#discussion_r1666643777 self.follows_heading = True if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( line_height=( self.line_height_stack[-1] if self.line_height_stack else None ), top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) if tag == "ul": self.indent += 1 bullet_char = attrs_dict.get("type") or self.ul_bullet_char # like browsers, an unknown type keeps the default marker; # a single character is still used as the bullet itself if len(bullet_char) > 1 and bullet_char.lower() not in ( "disc", "circle", "square", "none", ): bullet_char = self.ul_bullet_char self.bullet.append(bullet_char) line_height_str = css_style.get( "line-height", attrs_dict.get("line-height") ) # "line-height" attributes are not valid in HTML, # but we support it for backward compatibility, # because fpdf2 honors it since 2.6.1 and PR #629 # YYY parse and convert non-float line_height values # Invalid line-height: ignored, the default value is used line_height = _parse_line_height(line_height_str) self.line_height_stack.append(line_height) if self.indent == 1: tag_style = self.tag_styles[tag] if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( line_height=0, top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) self._write_paragraph("\u00a0") self._end_paragraph() if tag == "ol": self.indent += 1 start = 1 if "start" in attrs_dict: start_str = attrs_dict["start"] or "1" try: start = int(start_str) except ValueError: start = 1 self.bullet.append(start - 1) ol_type = attrs_dict.get("type") or "1" # like browsers, an unknown type (they are case-sensitive) gives numbers self.ol_type[self.indent] = ( ol_type if ol_type in ("1", "a", "A", "i", "I") else "1" ) line_height_str = css_style.get("line-height") or attrs_dict.get( "line-height" ) # "line-height" attributes are not valid in HTML, # but we support it for backward compatibility, # because fpdf2 honors it since 2.6.1 and PR #629 # YYY parse and convert non-float line_height values # Invalid line-height: ignored, the default value is used line_height = _parse_line_height(line_height_str) self.line_height_stack.append(line_height) if self.indent == 1: tag_style = self.tag_styles[tag] if isinstance(tag_style, TextStyle): t_margin = tag_style.t_margin b_margin = tag_style.b_margin l_margin = tag_style.l_margin else: t_margin = b_margin = l_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) self._new_paragraph( line_height=0, top_margin=t_margin, bottom_margin=b_margin, indent=l_margin, ) self._write_paragraph("\u00a0") self._end_paragraph() if tag == "li": prev_text_color = self.pdf.text_color self.pdf.text_color = self.li_prefix_color if self.bullet: bullet = self.bullet[self.indent - 1] else: # Allow <li> to be used outside of <ul> or <ol>. bullet = self.ul_bullet_char if not isinstance(bullet, int): bullet = ul_prefix(bullet, self.pdf.is_ttf_font) if not isinstance(bullet, str): bullet += 1 # like browsers, <li value="N"> numbers this item N and the next ones from there try: bullet = int((attrs_dict.get("value") or "").strip()) except ValueError: pass self.bullet[self.indent - 1] = bullet ol_type = self.ol_type[self.indent] bullet = f"{ol_prefix(ol_type, bullet)}." tag_style = self.tag_styles[tag] if isinstance(tag_style, TextStyle): b_margin = tag_style.b_margin l_margin = tag_style.l_margin t_margin = tag_style.t_margin else: b_margin = l_margin = t_margin = 0.0 l_margin = self._normalize_l_margin(l_margin) numeric_indent = 0.0 if isinstance(l_margin, Align) else l_margin self._new_paragraph( line_height=( self.line_height_stack[-1] if self.line_height_stack else None ), indent=numeric_indent * self.indent, top_margin=t_margin, bottom_margin=b_margin, bullet=bullet, ) self.pdf.text_color = prev_text_color if tag == "font": self.style_stack.append( FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) ) if _without_transparent(attrs_dict.get("color")) is not None: self.font_color = color_as_decimal(attrs_dict["color"]) if "font-size" in css_style: font_size_str = css_style.get("font-size") or "" try: # like browsers, a CSS length such as "14pt" or "12px"; # a number without a unit is still read as points font_size = resolve_length(font_size_str) # like browsers, a negative or infinite font size is ignored if math.isfinite(font_size) and font_size >= 0: self.font_size_pt = font_size except ValueError: pass elif "size" in attrs_dict: font_size_str = attrs_dict.get("size") or "" try: font_size = float(font_size_str) if math.isfinite(font_size) and font_size >= 0: self.font_size_pt = font_size except ValueError: pass if "face" in attrs_dict: face = attrs_dict.get("face") or "" # pylint: disable=protected-access catalog = ( self.pdf._resource_catalog # pyright: ignore[reportPrivateUsage] ) # bold and italic select the font file; underline and strikethrough do not style = "".join(c for c in self.font_emphasis.style if c in "BI") try: # like browsers, the first available font of a list such as # "Arial, Helvetica, sans-serif"; set_font() then adds it, # with its checks (such as PDF/A requiring embedded fonts) self.font_family = catalog.resolve_font_family(face, style) except KeyError: # no font of the list is available: set_font() reports it, as before self.font_family = face.lower() if tag == "table": if self.table is not None: parent = self.td_th["tag"] if self.td_th is not None else "table" raise NotImplementedError( f"Unsupported nested HTML tags inside <{parent}> element: <table>" ) self._end_paragraph() width: Optional[float] = None width_str = css_style.get("width") or attrs_dict.get("width") if width_str: width_str = width_str.strip() if width_str.endswith("%"): width = self.pdf.epw * _parse_html_percentage(width_str) / 100 else: width = _parse_html_dimension(width_str) / self.pdf.k if width <= 0: # like browsers, an invalid width is ignored width = None elif width > self.pdf.epw: LOGGER.warning( 'Table width="%s" is wider than the page: using the page width', width_str, ) width = self.pdf.epw if "border" not in attrs_dict: # default borders borders_layout = ( "HORIZONTAL_LINES" if self.table_line_separators else "SINGLE_TOP_LINE" ) else: borders_str = attrs_dict["border"] or "" try: if int(borders_str) > 0: # explicitly enabled borders borders_layout = ( "ALL" if self.table_line_separators else "NO_HORIZONTAL_LINES" ) else: # explicitly disabled borders borders_layout = "NONE" except ValueError: borders_layout = "NONE" align = Align.coerce(attrs_dict.get("align") or "CENTER") padding = None if "cellpadding" in attrs_dict: pad_val = attrs_dict["cellpadding"] match = unit_splitter.match((pad_val or "").strip()) if match and not match.group("unit"): try: padding = float(match.group("value")) except ValueError: padding = 0.0 else: padding = _parse_html_dimension(pad_val) / self.pdf.k sp_val = attrs_dict.get("cellspacing") if sp_val is not None: match = unit_splitter.match((sp_val or "").strip()) if match and not match.group("unit"): try: spacing = float(match.group("value")) except ValueError: spacing = 0.0 else: spacing = _parse_html_dimension(sp_val) / self.pdf.k if spacing < 0: # An invalid (negative) cellspacing is ignored, like browsers do spacing = 0.0 else: spacing = 0.0 self.first_row_widths = [] self.table = Table( self.pdf, align=align, borders_layout=borders_layout, line_height=self.font_size_pt / self.pdf.k * self.TABLE_LINE_HEIGHT, width=width, padding=padding, gutter_width=spacing, gutter_height=spacing, ) self._ln() if tag == "tr": if not self.table: raise FPDFException("Invalid HTML: <tr> used outside any <table>") self.tr = {k.lower(): v for k, v in attrs_dict.items()} self.table_row = self.table.row() if tag in ("td", "th"): if not self.table or not self.table_row: raise FPDFException(f"Invalid HTML: <{tag}> used outside any <tr>") self.td_th = {k.lower(): v for k, v in attrs_dict.items()} self.td_th["tag"] = tag if tag == "th": if "align" not in self.td_th: self.td_th["align"] = "CENTER" self.td_th["b"] = True elif len(self.table.rows) == 1 and not self.table_row.cells: # => we are in the 1st <tr>, and the 1st cell is a <td> # => we do not treat the first row as a header # pylint: disable=protected-access self.table._first_row_as_headings = ( False # pyright: ignore[reportPrivateUsage] ) self.table._num_heading_rows = 0 # pyright: ignore[reportPrivateUsage] if "height" in attrs_dict: LOGGER.warning( 'Ignoring unsupported height="%s" specified on a <%s>', attrs_dict["height"], tag, ) cell_width: Optional[tuple[float, bool]] = None if "width" in attrs_dict: width_str = (attrs_dict["width"] or "0").strip() if len(self.table.rows) == 1: # => first table row if width_str.endswith("%"): cell_width = (_parse_html_percentage(width_str), True) else: cell_width = (_parse_html_dimension(width_str), False) else: LOGGER.warning( 'Ignoring width="%s" specified on a <%s> that is not in the first <tr>', width_str, tag, ) if len(self.table.rows) == 1: # a cell that spans several columns gives each of them an equal part span = _parse_html_span(attrs_dict.get("colspan")) if cell_width is None: self.first_row_widths.extend([None] * span) else: self.first_row_widths.extend( [(cell_width[0] / span, cell_width[1])] * span ) if cell_width is not None: # pylint: disable=protected-access self.table._col_widths = [ w[0] for w in self.first_row_widths if w is not None ] if tag == "img" and "src" in attrs_dict: width = _parse_html_dimension(attrs_dict.get("width")) / self.pdf.k height = _parse_html_dimension(attrs_dict.get("height")) / self.pdf.k if self.table_row: # => <img> in a <table> if width or height: LOGGER.warning( 'Ignoring unsupported "width" / "height" set on <img> element' ) if self.align: LOGGER.warning("Ignoring unsupported <img> alignment") self.table_row.cell(img=attrs_dict["src"], img_fill_width=True) assert self.td_th is not None self.td_th["inserted"] = True self._take_table_anchors() return x: float | Align = self.pdf.get_x() if self.align: x = self.align info = self.pdf.image( self.image_map(attrs_dict["src"] or ""), x=x, w=width, h=height, link=self.href, ) # targets point to the top of the image, after any page break it caused for anchor in self._pending_anchors: self.pdf.set_link(name=anchor, y=self.pdf.y - info.rendered_height) self._pending_anchors.clear() if tag == "toc": self._end_paragraph() self.pdf.set_font( family=self.font_family, size=self.font_size_pt, style=self.font_emphasis.style, ) if self.font_color != self.pdf.text_color and self.font_color is not None: self.pdf.set_text_color(self.font_color) self.pdf.insert_toc_placeholder( self.render_toc, pages=int(attrs_dict.get("pages") or "1") ) if tag == "table" or self.table is not None: # table cells are not rendered as paragraphs: the row position is used self._take_table_anchors() if tag == "sup": self.pdf.char_vpos = CharVPos.SUP if tag == "sub": self.pdf.char_vpos = CharVPos.SUB if tag == "title": self._in_title = True if tag in ("style", "script"): self._in_style_or_script = True if css_style.get("break-after") == "page": if tag in ("br", "hr", "img"): self._end_paragraph() # pylint: disable=protected-access self.pdf._perform_page_break() # pyright: ignore[reportPrivateUsage] else: self._page_break_after_paragraph = True def put_link(self, text: str) ‑> None-
Expand source code Browse git
def put_link(self, text: str) -> None: "Insert a hyperlink" prev_style = FontFace( family=self.font_family, emphasis=self.font_emphasis, size_pt=self.font_size_pt, color=self.font_color, ) tag_style = self.tag_styles["a"] if tag_style.color: self.font_color = tag_style.color self.font_family = tag_style.family or self.font_family self.font_size_pt = tag_style.size_pt or self.font_size_pt if tag_style.emphasis: self.font_emphasis |= tag_style.emphasis self._write_paragraph(text, link=self.href) # Restore previous style: self.font_family = prev_style.family or self.font_family self.font_size_pt = prev_style.size_pt or self.font_size_pt self.font_emphasis = prev_style.emphasis or TextEmphasis.NONE self.font_color = prev_style.colorInsert a hyperlink
def render_toc(self,
pdf: FPDF,
outline: list[OutlineSection])-
Expand source code Browse git
def render_toc(self, pdf: "FPDF", outline: list[OutlineSection]) -> None: "This method can be overridden by subclasses to customize the Table of Contents style." pdf.ln() for section in outline: link = pdf.add_link(page=section.page_number) text = f"{' ' * section.level * 2} {section.name}" text += f" {'.' * (60 - section.level * 2 - len(section.name))} {section.page_number}" pdf.multi_cell( w=pdf.epw, h=pdf.font_size, text=text, new_x=XPos.LMARGIN, new_y=YPos.NEXT, link=link, )This method can be overridden by subclasses to customize the Table of Contents style.
class HTMLMixin (*args: Any, **kwargs: Any)-
Expand source code Browse git
class HTMLMixin: """ [**DEPRECATED since v2.6.0**] You can now directly use the `FPDF.write_html()` method """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) warnings.warn( ( "The HTMLMixin class is deprecated since v2.6.0. " "Simply use the FPDF class as a replacement." ), DeprecationWarning, stacklevel=get_stack_level(), )[DEPRECATED since v2.6.0] You can now directly use the
FPDF.write_html()method