python - 使用 Wea​​syprint 的 PDF 输出不显示图像(Django)

标签 python html django pdf weasyprint

我正在尝试使用 Wea​​syprint 库在 Django 上输出 PDF,但图像没有出现在生成的 PDF 上。我已经为图像尝试了相对和静态 URL,但即使是静态 URL 也不显示图像。在 chrome 上打开 HTML 本身时,图像会显示。

这是我在 views.py 文件中的 pdf 生成 View :

def pdf_generation(request, some_slug)
    stud = Student.objects.get(some_slug=some_slug)
    studid = stud.some_slug
    context = {'studid':studid}
    html_string = render_to_string('templates/pdf_gen.html', context)
    html = HTML(string=html_string)
    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')]);
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'
    return response

这是图像的 HTML 部分:

<DIV id="p1dimg1">
<IMG src="{% static 'img/image.jpg' %}" alt="">
</DIV>

还有 CSS:

#page_1 #p1dimg1 {position:absolute;top:0px;left:0px;z-
index:-1;width:792px;height:1111px;}
#page_1 #p1dimg1 #p1img1 {width:792px;height:1111px;}

非常感谢

最佳答案

修复者:

添加 base_url=request.build_absolute_uri() 以便

html = HTML(string=html_string)

成为

html = HTML(string=html_string, base_url=request.build_absolute_uri())

这将允许在 HTML 文件中使用相对 URL。

对于图像,出于某种原因似乎只有 PNG 图像有效。

对于要在 PDF 上显示的 HTML 样式,请根据 Weasyprint 文档添加 presentational_hints=True:

    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')], presentational_hints=True);

关于python - 使用 Wea​​syprint 的 PDF 输出不显示图像(Django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48988707/

相关文章:

python - SQLAlchemy 中的僵尸连接

python - solve_ivp(ODE 求解器)的实现

php - 使用 PHP 从 SQL 数据库传递选择值

javascript - 获得按下按钮对回车键的影响

html - col-xs 不适用于小于 768px 的媒体屏幕

python - 创建 Stripe 订阅 Python

python - 从 pandas 数据框中提取多年三个月系列(冬季)

python - Google AppEngine 复杂的 WHERE 条件

django - FATAL : too many connections for role: Heroku/django, 仅在使用 ASGI 时

python - 何时以及为何使用 Django 开发服务器?