Skip to content

Instantly share code, notes, and snippets.

@waylan
Created Jul 1, 2021
Embed
What would you like to do?
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