用法: mkCompile.py AAA.md --pdf 即可把markdown格式的文件转换成pdf。 转载请注明本文地址和出处。 直接上代码:

#!/usr/bin/env python3
#coding=utf-8

import os,time,sys
import markdown
import subprocess
from markdown.extensions.wikilinks import WikiLinkExtension

def markdown2html(markdown_text):
    '''
    Convert markdown text to HTML. with extensions.
    :param markdown_text:   The markdown text.
    :return:  The HTML text.
    '''
    html = markdown.markdown(
        markdown_text,
        output_format="html5",
        extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.toc',
            'markdown.extensions.codehilite',
            'markdown.extensions.meta'
        ]
    )
    return html

def saveBin(filename, content):
    f = open(filename,mode="wb+")
    f.write(content)
    f.flush()
    f.close()
    print(filename ,'has been saved.')

def run(command):
    if not command:
        raise Exception("command is invalid")
    else:
        p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.wait()
        out, err = p.communicate()
        return out

def fileProcess01(content):
    content = content.replace("[ ]",'<input type="checkbox" aria-label="Done" disabled>')
    content = content.replace("[x]",'<input type="checkbox" aria-label="Not Done" checked disabled>')
    content = content.replace("[-]",'<input type="checkbox" aria-label="Wont Done" checked disabled><del>【Wont Fix】</del>')
    return content

def fConvert1(infilename, outfilename):
    fileOrgin = open(infilename)
    hin=""
    hout=""
    for p in fileOrgin:
        hin = "%s%s"%(hin,p)
    hout = markdown2html(hin)

    htmltemplate = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
    {{}}
    </body>
    '''
    hout= htmltemplate.replace("{{}}", hout)
    hout= fileProcess01(hout)
    saveBin(outfilename, hout.encode())

def fConvert2():
    mk = markdown.Markdown(output_format="html5",
        extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.toc',
            'markdown.extensions.codehilite',
            'markdown.extensions.meta'
        ]
    )
    mk.convertFile("TODO.md","TODO.html","utf-8")

def toPDF(infilename, outfilename):
    run('wkhtmltopdf '+ infilename + ' ' + outfilename)
    print(outfilename ,'has been saved.')

def main():
    print('''
    ------------------------------------------------------
    Using wkhtmltopdf to convert html to pdf. If you have not installed wkhtmltopdf please:
    sudo apt install wkhtmltopdf
    ------------------------------------------------------
    Example: mkCompile.py AAA.md --pdf
    ''')
    if(len(sys.argv)>1):
        infilename = sys.argv[1]
        outfilename =  infilename+".html"
        fConvert1(infilename,outfilename)
        if(len(sys.argv)>2 and sys.argv[2] == '--pdf'):
            toPDF(outfilename , infilename+".pdf")


if __name__ == '__main__':
    main()