typemytype / drawbot

http://www.drawbot.com
Other
402 stars 63 forks source link

support html/markdown in a attributed string #445

Open typemytype opened 2 years ago

typemytype commented 2 years ago

just to keep it public and a set of drawBot addons would be nice to have as a set of snippets/gists which are somehow accessible

import AppKit

def appendHTML(self, html):
    htmlString = AppKit.NSString.stringWithString_(html)
    txt, _, _ = AppKit.NSAttributedString.alloc().initWithData_options_documentAttributes_error_(
        htmlString.dataUsingEncoding_(AppKit.NSUTF8StringEncoding),
        {AppKit.NSDocumentTypeDocumentAttribute: AppKit.NSHTMLTextDocumentType, AppKit.NSCharacterEncodingDocumentAttribute: AppKit.NSUTF8StringEncoding},
        None, None)
    self._attributedString.appendAttributedString_(txt)
    self._attributedString.appendAttributedString_(AppKit.NSAttributedString.alloc().initWithString_("\n"))

def appendMarkdown(self, md, style=None):
    import markdown
    from markdown.extensions.toc import TocExtension as markdownTocExtension
    from markdown.extensions.tables import TableExtension as markdownTableExtension
    from markdown.extensions.fenced_code import FencedCodeExtension as markdownFencedCodeExtension
    from markdown.extensions.codehilite import CodeHiliteExtension as markdownCodeHiliteExtension

    convertedMarkdown = markdown.markdown(md, extensions=[
        markdownTableExtension(),
        markdownTocExtension(permalink=False, toc_depth='2-3'),
        markdownFencedCodeExtension(),
        markdownCodeHiliteExtension()
    ])
    print(convertedMarkdown)
    if style is None:
        style = ""
    self.appendHTML(f"""<html>
<head>
    <meta charset="UTF-8">
    <style>
        {style}
    </style>
</head>
<body>
{convertedMarkdown}
</body>
</html>
""")

FormattedString().__class__.appendHTML = appendHTML
FormattedString().__class__.appendMarkdown = appendMarkdown  

html = """<html>
<style>
body {
    font-family:"Helvetica";
    color: red;
}
h1 {
    color: blue;
}
</style>
<body>
<h1>foo bar</h1>
hello world
<h2>foo bar</h2>
more
</body>
</html>"""

t = FormattedString()
t.appendHTML(html)

md = """# some title

more info

## subtitle
### foo bar

foo bar
----
qd

"""
t.appendMarkdown(md, style="h1 {color:blue}")

textBox(t, (10, 10, 900, 900))