Skip to content

Instantly share code, notes, and snippets.

@waylan
Created July 1, 2021 17:40
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 waylan/f0f9465a75d80c4dcc8492a8f44b285b to your computer and use it in GitHub Desktop.
Save waylan/f0f9465a75d80c4dcc8492a8f44b285b to your computer and use it in GitHub Desktop.
import markdown
import re
import yaml
from yaml import SafeLoader
from wp2pdf import html2pdf
BLOCK_RE = re.compile(r'^-{3}[ \t]*\n(.*?\n)(?:\.{3}|-{3})[ \t]*\n', re.UNICODE|re.DOTALL)
def get_data(doc):
"""
Extract meta-data from a text document.
Returns a tuple of document and data.
"""
data = {}
m = BLOCK_RE.match(doc)
if m:
try:
data = yaml.load(m.group(1), SafeLoader)
if isinstance(data, dict):
doc = doc[m.end():].lstrip('\n')
else:
data = {}
except:
pass
return doc, data
def md2pdf(input, output):
with open(input, 'r') as fd:
doc, data = get_data(fd.read())
md_opts = data.get('md_opts', {})
pdf_opts = data.get('pdf_opts', {})
html = markdown.markdown(doc, **md_opts)
html2pdf(html, output, **pdf_opts)
if __name__ == '__main__':
md2pdf('myexample.md', 'md.pdf')
md_opts pdf_opts
extensions extension_configs
attr_list
fenced_code
codehilite
codehilite
noclasses
true
headers header_styles styles
EXAMPLE
color: red;
h1 { color: darkblue; } .foo { color: orange; }

An example document

This PDF is generated{ .foo } from a Markdown file.

from md2wpdf import md2pdf
md2pdf('example.md', 'md.pdf')
@waylan
Copy link
Author

waylan commented Jul 1, 2021

The output looks like this:

Untitled

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment