python转换markdown为pdf

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

文章目录

方法一:使用 WeasyPrint

需要安装 WeasyPrintmarkdown 包:

pip install weasyprint markdown
import markdown
from weasyprint import HTML, CSS

# 读取Markdown文件
with open('example.md', 'r', encoding='utf-8') as f:
    text = f.read()
    html = markdown.markdown(text, output_format='html5')

# 将HTML转换为PDF
HTML(string=html).write_pdf("output_weasyprint.pdf")

方法二:使用 pdfkitwkhtmltopdf

需要安装 pdfkitmarkdown 包:

pip install pdfkit markdown
apt install wkhtmltopdf
import pdfkit
import markdown

# 读取Markdown文件
with open('example.md', 'r', encoding='utf-8') as f:
    text = f.read()
    html = markdown.markdown(text)

# 添加中文字体样式到HTML
html_with_style = f"""
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {{
            font-family: 'SimHei', 'Microsoft YaHei', sans-serif;
            font-size: 12pt;
        }}
    </style>
</head>
<body>
{html}
</body>
</html>
"""

# 使用额外参数启用本地文件访问(用于加载字体)
pdfkit.from_string(html_with_style, 'output_pdfkit.pdf', options={'enable-local-file-access': None})

方法三:使用 md2pdf

pip install md2pdf weasyprint
from md2pdf.core import md2pdf

def convert_md_to_pdf(input_md_file_path, output_pdf_file_path):
    """
    Converts a Markdown file to a PDF file with Chinese font support.
    """
    with open(input_md_file_path, 'r', encoding='utf-8') as f:
        text = f.read()

    # 转换并应用样式
    md2pdf(output_pdf_file_path, md_content=text)

方法四:使用 pandocwkhtmltopdf

pip install pypandoc
apt install pandoc wkhtmltopdf
import pypandoc

def md_to_pdf_pandoc(input_md, output_pdf):
    try:
        output = pypandoc.convert_file(
            input_md, 'pdf', outputfile=output_pdf,
            extra_args=['--pdf-engine=wkhtmltopdf']  # 使用 xelatex 替代 pdflatex
        )
        print(f"PDF 已生成:{output_pdf}")
    except Exception as e:
        print("转换失败:", str(e))

不支持公式渲染。

安装 Tex 组件

sudo apt update
sudo apt install texlive-latex-base texlive-fonts-recommended texlive-fonts-extra texlive-latex-extra texlive-xetex  texlive-full

使用 xelatex 引擎,下载模板 https://github.com/Wandmalfarbe/pandoc-latex-template?tab=readme-ov-file,放到 /root/.local/share/pandoc/templates

import pypandoc

def md_to_pdf_pandoc(input_md, output_pdf):
    try:
        # 使用自定义 LaTeX 模板或内联样式
        output = pypandoc.convert_file(
            input_md, 'pdf',
            outputfile=output_pdf,
            extra_args=[
                '--pdf-engine=xelatex',
                '-V', 'documentclass=ctexart',  # 使用 ctex 宏包支持中文
                '-V', 'CJKmainfont=SimHei',     # 设置中文字体
                '-V', 'monofont=DejaVu Sans Mono',  # 设置等宽字体以支持代码块
                '-V', 'geometry:margin=1in',    # 设置页边距
                '--template=eisvogel',  # 使用自定义模板
                '--listings',
                '--highlight-style=pygments'    # 使用语法高亮风格(带背景色)
            ]
        )
        print(f"PDF 已生成:{output_pdf}")
    except Exception as e:
        print("转换失败:", str(e))

# 调用函数
md_to_pdf_pandoc('example.md', 'out.pdf')   # from https://michael.blog.csdn.net/

效果对比

原始 MDWeasyPrintpdfkitmd2pdfpandocpandoc+tex
代码块、公式、表格都不行