You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Markdown转PDF报错求助:已测试代码仍存问题

Markdown转PDF报错的解决办法
  • 必须安装wkhtmltopdf工具并配置
    pdfkit不是纯Python实现,它依赖wkhtmltopdf这个外部工具,只装Python库没用:

    • Windows:下载安装wkhtmltopdf后,要么把安装目录下的bin文件夹路径加入系统环境变量,要么在代码里手动指定路径:
      import markdown2
      import pdfkit
      
      config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
      filename = "sample.md"
      
      with open(filename, "r") as file:
          markdown_text = file.read()
      
      html_text = markdown2.markdown(markdown_text)
      pdfkit.from_string(html_text, "output.pdf", configuration=config)
      
    • macOS:通过brew安装brew install wkhtmltopdf
    • Linux:用包管理器安装,比如Ubuntu执行sudo apt-get install wkhtmltopdf
  • 优化Markdown转HTML的兼容性
    如果原Markdown包含表格、代码块等复杂格式,给markdown2加上对应扩展避免HTML格式错误:

html_text = markdown2.markdown(markdown_text, extras=['tables', 'fenced-code-blocks', 'strike-through'])
  • 排查文件路径与权限
    • 确认sample.md在脚本的当前工作目录,或者改用绝对路径指定文件位置
    • 确保当前用户有权限在目标目录生成output.pdf

内容的提问来源于stack exchange,提问作者yusuf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:52:39