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

Django中pdfkit渲染带模板变量的HTML转PDF出现空白页求助

解决Django中pdfkit生成空白PDF或选择django-weasyprint的方案

先排查pdfkit的空白页问题

1. 确认渲染后的HTML是否正确

先把render_to_string生成的内容导出到本地,检查变量循环是否正常渲染:

html_content = render_to_string('timeline_template.html', {'items': your_data})
# 写入本地文件查看实际渲染结果
with open('rendered.html', 'w', encoding='utf-8') as f:
    f.write(html_content)

打开rendered.html确认有没有数据,有没有模板语法错误(比如for循环没闭合、变量名拼写错误)。

2. 检查pdfkit的wkhtmltopdf配置

pdfkit依赖wkhtmltopdf工具,必须确保路径配置正确:

import pdfkit
# 根据系统配置wkhtmltopdf路径
config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')  # Linux示例
# Windows示例: 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
# macOS示例: '/usr/local/bin/wkhtmltopdf'

# 开启调试模式查看报错信息
pdf_content = pdfkit.from_string(
    html_content,
    False,
    configuration=config,
    options={'verbose': '', 'encoding': 'UTF-8'}
)

如果未安装wkhtmltopdf,先对应系统安装后再配置路径。

3. 修复模板样式问题

静态HTML正常但动态生成的PDF空白,大概率是CSS路径问题:

  • 把CSS内联到模板的<style>标签里,避免用相对路径引用外部CSS
  • 或者用Django的static标签生成完整绝对URL(确保静态文件可被访问,本地开发时用完整http路径)

改用django-weasyprint的方案

如果pdfkit问题难排查,先解决WeasyPrint的系统依赖,再用django-weasyprint:

1. 安装系统依赖

  • Ubuntu/Debian:
    sudo apt-get install libpango-1.0-0 libharfbuzz0b libpangoft2-1.0-0 libffi-dev libcairo2
    
  • macOS:
    brew install pango cairo gdk-pixbuf libffi
    
  • Windows:用conda安装预编译包
    conda install -c conda-forge weasyprint
    

2. 安装django-weasyprint并使用

pip install django-weasyprint

编写视图直接返回PDF响应:

from django_weasyprint import WeasyTemplateResponse

def timeline_pdf_view(request):
    items = YourModel.objects.all()  # 替换为你的数据查询逻辑
    return WeasyTemplateResponse(
        request,
        'timeline_template.html',
        context={'items': items},
        filename='timeline.pdf'
    )

模板里正常使用{% static %}引用静态资源,django-weasyprint会自动处理路径问题。

总结

优先排查pdfkit的渲染内容、wkhtmltopdf配置和模板样式,这些是空白页的常见原因;如果依赖问题难以解决,换成django-weasyprint更贴合Django生态,处理模板和静态资源更省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:53:09