【发布时间】:2018-09-04 03:23:05
【问题描述】:
这是我找到的假设解决方案。 https://stackoverflow.com/a/2180417
我正在尝试实现它,但我无法做到。
这是我当前的代码:
utils.py
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
views.py
from django.http import HttpResponse
from django.views.generic import View
from yourproject.utils import render_to_pdf #created in step 4
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
data = {
'today': datetime.date.today(),
'amount': 39.99,
'customer_name': 'Cooper Mann',
'order_id': 1233434,
}
pdf = render_to_pdf('pdf/invoice.html', data)
return HttpResponse(pdf, content_type='application/pdf')
如果我只是渲染一个普通的模板,一切都会正确加载,所以我知道问题出在这部分过程中。 invoice.html 模板包含一个 URL,例如 /home/images/products/1231
<img src='{{ photo.url }}'>
【问题讨论】:
标签: python django python-3.x python-2.7 xhtml2pdf