python如何把md文件转为pdf
时间: 2025-03-27 07:09:12 浏览: 59
### Python 将 Markdown 文件转换为 PDF
#### 使用 `pdfkit` 和 `markdown` 库实现转换
为了将 Markdown 文件转换成 PDF,可以采用组合使用 `pdfkit` 和 `markdown` 这两个库的方式。首先需要安装这两个库以及依赖项 wkhtmltopdf。
```bash
pip3 install markdown pdfkit
```
wkhtmltopdf 是一个命令行工具,用于将 HTML 转换成 PDF。可以从官方网站下载并按照说明进行安装[^3]。
下面是具体的代码示例:
```python
import codecs
import markdown
import pdfkit
def convert_md_to_pdf(input_md, output_pdf):
"""
Converts a Markdown file into a PDF document.
:param input_md: Path to the input Markdown (.md) file.
:param output_pdf: Desired path for the generated PDF file.
"""
# Read and parse the Markdown content from the given .md file
with codecs.open(input_md, 'r', encoding='utf-8') as f:
md_content = f.read()
# Convert parsed Markdown text into HTML format
html_content = markdown.markdown(md_content)
# Write temporary HTML file including meta tag to prevent Chinese character issues
temp_html_path = "temp.html"
with codecs.open(temp_html_path, 'w', encoding='utf-8') as f:
f.write('<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>')
f.write(html_content)
# Use pdfkit to generate final PDF based on created HTML page
pdfkit.from_file(temp_html_path, output_pdf)
if __name__ == "__main__":
# Example usage of function defined above
convert_md_to_pdf('example.md', 'output.pdf')
```
这段脚本会读取指定路径下的 `.md` 文件内容,并将其转化为 HTML 字符串;接着写入临时 HTML 文件中(加入必要的元数据标签来解决可能存在的编码问题),最后调用 `pdfkit` 完成从 HTML 到 PDF 的转变过程。
阅读全文
相关推荐

















