一尘不染

django-pisa:向PDF输出添加图像

django

我正在使用网络上的标准示例(http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html)将django视图/模板转换为PDF。

是否有一种“简便”的方式将图像(来自URL或服务器上的引用)包括在模板中,以便它们显示在PDF上?


阅读 516

收藏
2020-03-27

共1个答案

一尘不染

我得到了图像。代码如下:

from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import RequestContext
from django.conf import settings
import ho.pisa as pisa
import cStringIO as StringIO
import cgi
import os

def dm_monthly(request, year, month):
    html  = render_to_string('reports/dmmonthly.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request))
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )
    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='application/pdf')
    return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))

def fetch_resources(uri, rel):
    path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

    return path
2020-03-27