def process_markdown(self, markdown_string: str, paragraph_style: str = "p"): walker = Parser().parse(markdown_string).walker() event = walker.nxt() buf = "" while event is not None: node, entering = event["node"], event["entering"] node_type = node.t if node_type == "text": buf += node.literal if node_type == "softbreak": buf += " " if node_type == "linebreak": buf += "<br />" if node_type == "link": buf += f'<a href="{escape(node.destination)}">' if entering else "</a>" if node_type == "emph": buf += "<em>" if entering else "</em>" if node_type == "strong": buf += "<strong>" if entering else "</strong>" if node_type == "paragraph" and not entering: style = paragraph_style if node.parent.t == "item": style = "ul_li" if node.parent.parent.list_data[ "type"] == "bullet" else "ol_li" self.parts.append(Paragraph(buf, PDF_STYLES[style])) buf = "" event = walker.nxt()
def truncate_md(markdown_string: str, *, limit: int = 200) -> str: walker = Parser().parse(markdown_string).walker() event = walker.nxt() buf = "" while event is not None: if event["node"].t == "text": buf += event["node"].literal break # this limits results to first paragraph only event = walker.nxt() return f"{buf[:limit]}..." if len(buf) > limit else buf