在 Django 中将 CSS 添加到 Pdfkit?

dio*_*nes 1 python pdf django pdfkit

我无法将我的 css 添加到我的 PdfKit 代码中。

HTML 中的普通静态链接不起作用。

<link href="{% static 'css/print.css' %}" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)

我在视图中看到了这种方法,但找不到在 Django 中链接 css 文件的方法。

css = 'print.css'
pdfkit.from_file('file.html', css=css)
Run Code Online (Sandbox Code Playgroud)

还为 Flask 找到了这个答案 - 如何为 Django 做同样的事情?

如何在 Flask 应用程序中将样式表文件链接到 pdfkit?

谢谢。

Bor*_*rut 8

您需要添加完整路径。代替

<link href="{% static 'css/print.css' %}" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)

你会用

<link href="http://localhost/static/css/print.css" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)

您发现的第二种方法也有效,但您再次需要使用文件的完整路径,例如:

import os
from django.conf import settings

css = os.path.join(settings.STATIC_ROOT, 'css', 'print.css')
pdfkit.from_file('file.html', css=css)
Run Code Online (Sandbox Code Playgroud)

在后一种情况下,您还需要提供完整路径file.html。但是,在 Django 中,您可能宁愿先呈现file.html为字符串,然后使用呈现的 html 来创建 PDF。就像是:

import os
from django.conf import settings
from django.template.loader import render_to_string

t = render_to_string('file.html', {})
css = os.path.join(settings.STATIC_ROOT, 'css', 'print.css')

pdf = pdfkit.from_string(t, 'file.pdf', css=css)
Run Code Online (Sandbox Code Playgroud)

...或者如果您想返回 PDF 作为响应

from django.http import HttpResponse

pdf = pdfkit.from_string(t, False, css=css)
response = HttpResponse(pdf)
response['Content-Type'] = 'application/pdf'
response['Content-Disposition'] = 'attachment; filename = file.pdf'
return response
Run Code Online (Sandbox Code Playgroud)