Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kenkeiter
Created October 17, 2019 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenkeiter/c2336eda4a0021e1d62b7a3bfb0d46cc to your computer and use it in GitHub Desktop.
Save kenkeiter/c2336eda4a0021e1d62b7a3bfb0d46cc to your computer and use it in GitHub Desktop.
Quick markdown file to PDF routine.
import os
import markdown
from markdown_include.include import MarkdownInclude
import weasyprint
from mako.template import Template
HTML_BOILERPLATE_TEMPLATE = """
<html>
<head>
<style>{css}</style>
</head>
<body>{body}</body>
</html>
"""
def render_markdown_pdf(file_path, style_path, local={}):
"""
render_markdown renders a given markdown file as HTML.
"""
markdown_dir = os.path.dirname(file_path)
## load the markdown file, render it as a template
markdown_template = None
with open(file_path, 'r', encoding='utf-8') as fh:
markdown_template = fh.read()
# render the file as a template
markdown_template = Template(markdown_template).render(**local)
## render the file as HTML
# load the style sheet
css = None
with open(style_path, 'r') as fh:
css = fh.read()
markdown_incl = MarkdownInclude(configs={'base_path': markdown_dir})
body = markdown.markdown(
markdown_template,
extensions=['extra', markdown_incl, 'meta', 'tables'])
html = HTML_BOILERPLATE_TEMPLATE.format(css=css, body=body)
## convert the HTML to PDF
pdf = weasyprint.HTML(string=html, base_url=markdown_dir)
return pdf.write_pdf(None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment