Skip to content

Instantly share code, notes, and snippets.

@engineervix
Last active April 2, 2023 14:09
Show Gist options
  • Save engineervix/2385a54a4019b3f4526e to your computer and use it in GitHub Desktop.
Save engineervix/2385a54a4019b3f4526e to your computer and use it in GitHub Desktop.
convert markdown to html and pdf using Python
import markdown2 # pip install markdown2
import os
import sys
import pdfkit # for pdf output (uses wkhtml2pdf, which must be in your PATH)
# adapted from http://is.gd/yetava
# usage: python mkdown2html_and_pdf.py input.md your_custom_stylesheet.css
DEFAULT_EXTRAS = [
'fenced-code-blocks',
'footnotes',
'metadata',
'cuddled-lists',
'pyshell',
'smarty-pants',
'spoiler',
'tables'
]
PDF_OPTIONS = {
'page-size': 'A4',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8"
#'no-outline': None
}
output = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
"""
cssin = open(sys.argv[2])
output += cssin.read()
output += """
</style>
</head>
<body>
"""
mkin = open(sys.argv[1])
output += markdown2.markdown(mkin.read(), extras=DEFAULT_EXTRAS)
output += """</body>
</html>
"""
# remove the `.md` file extension using `os.path.splitext(filename)[0]`
htmlfile = os.path.splitext(sys.argv[1])[0] + ".html"
outfile = open(htmlfile, "w")
outfile.write(output)
outfile.close()
# create pdf
pdfkit.from_file(htmlfile, os.path.splitext(
htmlfile)[0] + ".pdf", options=PDF_OPTIONS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment