python markdown转pdf
时间: 2025-02-20 10:15:28 浏览: 57
### 如何使用Python将Markdown文件转换为PDF
为了实现从Markdown到PDF的转换,可以采用多种方法和技术栈。一种常见的方式是利用`pandoc`工具配合Python脚本完成此操作。另一种方式则是完全基于Python环境内的库来达成目标。
#### 方法一:借助Pandoc与Pygments
通过调用命令行工具`pandoc`,能够高效地处理不同格式间的转换工作。下面是一个简单的例子展示怎样在Python程序里集成这个流程[^1]:
```python
import subprocess
from pathlib import Path
def markdown_to_pdf(input_file, output_file):
result = subprocess.run(
['pandoc', str(input_file), '-o', str(output_file)],
capture_output=True,
text=True
)
if result.returncode != 0:
raise Exception(f"Pandoc conversion failed with error: {result.stderr}")
# Example usage
input_md = Path('example.md')
output_pdf = Path('example.pdf')
markdown_to_pdf(input_md, output_pdf)
```
这种方法依赖于外部软件`pandoc`的存在及其正确配置;因此,在部署之前需确认环境中已安装好该工具。
#### 方法二:纯Python解决方案——结合WeasyPrint和Mistune
对于希望保持项目纯粹性的开发者来说,也可以考虑仅依靠Python包来解决问题。这里推荐组合使用`mistune`解析器读取Markdown内容,并由`weasyprint`负责渲染HTML至PDF输出[^3]。
```python
from mistune import Markdown, HtmlRenderer
from weasyprint import HTML, CSS
from pathlib import Path
renderer = HtmlRenderer()
markdown_parser = Markdown(renderer)
css_style = """
body {
font-family: Arial;
}
h1 {
color: #4CAF50;
}
"""
def convert_markdown_to_pdf(markdown_path, pdf_path):
md_content = Path(markdown_path).read_text(encoding='utf8')
html_content = markdown_parser(md_content)
css = CSS(string=css_style)
document = HTML(string=html_content).write_pdf(stylesheets=[css])
with open(pdf_path, 'wb') as f:
f.write(document)
convert_markdown_to_pdf('sample.md', 'output.pdf')
```
上述代码片段展示了如何创建一个函数用于执行整个转换过程,包括加载Markdown源码、应用样式表以及保存最终产物。
阅读全文
相关推荐


















