# python转换markdown为pdf

**URL:** <https://forum.beginner.center/t/topic/2347>\
**Category:** 🛠工具与编程\
**Tags:** python, markdown\
**Created:** [2025 年11 月 3 日 02:45 UTC](https://forum.beginner.center/t/topic/2347 "2025-11-03T02:45:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![doggie](https://forum.beginner.center/user_avatar/forum.beginner.center/doggie/32/550_2.png) [@doggie](https://forum.beginner.center/u/doggie)\
发布日期： [2025 年11 月 3 日 02:45 UTC](https://forum.beginner.center/t/topic/2347/1 "2025-11-03T02:45:52Z")

</div>

> 本文由 [简悦 SimpRead](http://ksria.com/simpread/) 转码， 原文地址 [blog.csdn.net](https://blog.csdn.net/qq_21201267/article/details/149433077)

#### 文章目录

- 
  - [方法一：使用 `WeasyPrint`](#_WeasyPrint_1)
  - [方法二：使用 `pdfkit` 和 `wkhtmltopdf`](#_pdfkit__wkhtmltopdf_22)
  - [方法三：使用 `md2pdf`](#_md2pdf_59)
  - [方法四：使用 `pandoc` 和 `wkhtmltopdf`](#_pandoc__wkhtmltopdf_79)
  - [效果对比](#_136)

### 方法一：使用 `WeasyPrint`

需要安装 `WeasyPrint` 和 `markdown` 包：

```auto
pip install weasyprint markdown

```

```auto
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")

```

### 方法二：使用 `pdfkit` 和 `wkhtmltopdf`

需要安装 `pdfkit` 和 `markdown` 包：

```auto
pip install pdfkit markdown
apt install wkhtmltopdf

```

```auto
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`

```auto
pip install md2pdf weasyprint

```

```auto
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)

```

### 方法四：使用 `pandoc` 和 `wkhtmltopdf`

```auto
pip install pypandoc
apt install pandoc wkhtmltopdf

```

```auto
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](https://so.csdn.net/so/search?q=Tex&spm=1001.2101.3001.7020) 组件

```auto
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](https://github.com/Wandmalfarbe/pandoc-latex-template?tab=readme-ov-file)，放到 `/root/.local/share/pandoc/templates`

```auto
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/

```

### 效果对比

| 原始 MD | WeasyPrint | pdfkit | md2pdf | pandoc | pandoc+tex |
| --- | --- | --- | --- | --- | --- |
| ![](https://discoursecdn.beginner.center/original/2X/a/a841b7c203979a978ccc4e7516f37e7081841861.png) | ![](https://discoursecdn.beginner.center/original/2X/9/932384598997d544ca6e3cbf3615e73af54a52d0.png) | 代码块、公式、表格都不行 | ![](https://discoursecdn.beginner.center/original/2X/7/7f52e5ce1f2f4379a6562052c6754281987a1a75.png) | ![](https://discoursecdn.beginner.center/original/2X/9/9395624ee28b0c1d8241fe270f73f51a6eb464ba.png) | ![](https://discoursecdn.beginner.center/original/2X/e/e747672c4599c45758a97de0d30143d456291c35.png) |
