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

Django项目集成wkhtmltopdf下载PDF遇找不到可执行文件错误排查

Django HTML转PDF报错排查与解决

问题描述

我有一个Django项目,希望将其中的HTML页面下载为PDF文件。已正确下载wkhtmltopdf可执行文件,并在settings.py中进行了配置,但尝试下载PDF时出现以下错误:

No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

相关代码片段:

views.py

@login_required
def download_resume(request):
    # Retrieve data from your Django models
    personal_info = personalinfo.objects.filter(user=request.user).last()
    summaries = summary.objects.filter(user=request.user).last()
    experiences = experience.objects.filter(user=request.user)
    educations = education.objects.filter(user=request.user)
    certs = certificates.objects.filter(user=request.user)
    skillset = skills.objects.filter(user=request.user)

    # Generate the PDF content using a template
    template = get_template('template0.html')
    context = {
        'personal_info': personal_info,
        'summaries': summaries,
        'experiences': experiences,
        'educations': educations,
        'certs': certs,
        'skillset': skillset
    }

    # Render the template with the context data
    html_content = template.render(context)

    # Convert HTML to PDF using wkhtmltopdf
    pdf = pdfkit.from_string(html_content, False)

    # Create a response with the PDF content
    response = FileResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="resume.pdf"'

    return response

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

WKHTMLTOPDF_BIN_PATH = r'C:\Users\lulu\PycharmProjects\builderproject\wkhtmltopdf\binwkhtmltopdf.exe'

确认已下载wkhtmltopdf并在配置文件中注册,但点击下载按钮仍报错,请问可能是什么原因?


解决方法

  • 修复路径拼写错误
    你的WKHTMLTOPDF_BIN_PATH路径缺少反斜杠,binwkhtmltopdf.exe应为bin\wkhtmltopdf.exe,正确配置:

    WKHTMLTOPDF_BIN_PATH = r'C:\Users\lulu\PycharmProjects\builderproject\wkhtmltopdf\bin\wkhtmltopdf.exe'
    
  • 让pdfkit读取配置路径
    仅在settings.py配置无效,需在调用时传入路径:
    修改views.py中的PDF生成代码:

    import pdfkit
    from django.conf import settings
    
    # ...其他代码...
    
    config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDF_BIN_PATH)
    pdf = pdfkit.from_string(html_content, False, configuration=config)
    
  • 检查文件权限
    确保Django运行进程(PyCharm/服务器)拥有wkhtmltopdf.exe的读取和执行权限,右键文件→属性→安全,确认当前用户权限。

  • 验证可执行文件完整性
    直接双击wkhtmltopdf.exe,若弹出命令行窗口无报错则文件正常;若提示缺少dll,需重新下载带完整依赖的wkhtmltopdf版本。


内容的提问来源于stack exchange,提问作者developer-re

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:25:29