Skip to content

Instantly share code, notes, and snippets.

@gferreira
Last active May 7, 2026 10:32
Show Gist options
  • Select an option

  • Save gferreira/c8b8a143ff5e72f04b2e693ab6b4188a to your computer and use it in GitHub Desktop.

Select an option

Save gferreira/c8b8a143ff5e72f04b2e693ab6b4188a to your computer and use it in GitHub Desktop.
setting markdown text with CSS styles using DrawBot FormattedString
import AppKit
import markdown
from string import Template
htmlTemplate = Template("""\
<html>
<head>
<meta charset="UTF-8">
<style>
$cssCode
</style>
</head>
<body>
$htmlCode
</body>
</html>
""")
class MarkdownFormattedString(FormattedString):
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)
def appendMarkdown(self, markdownSrc, style=""):
markdownHTML = markdown.markdown(markdownSrc, extensions=['smarty', 'attr_list'])
html = htmlTemplate.substitute(cssCode=style, htmlCode=markdownHTML)
self.appendHTML(html)
markdownSrc = """\
# title
some info **bold** more info.
*the quick [brown](#) fox jumps.*
## subtitle
foo bar `monospaced` bar foo?
### sub-subtitle
"smarty pants"
this is a custom class
{: .custom }
"""
css = """\
body { font-family: 'Verdana'; font-size: 13pt; }
h1 { color: magenta; }
h2 { color: cyan; }
h3 { color: purple; font-family: serif; }
strong { color: green; }
em { color: orange; }
a { color: brown; text-decoration: none; }
.custom { font-family: 'Georgia'; color: lavender; }
"""
margin = 40
size('A4')
T = MarkdownFormattedString()
T.appendMarkdown(markdownSrc, style=css)
textBox(T, (margin, margin, width()-margin*2, height()-margin*2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment