Last active
April 2, 2023 14:09
-
-
Save engineervix/2385a54a4019b3f4526e to your computer and use it in GitHub Desktop.
convert markdown to html and pdf using Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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