35

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

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

4

7 回答 7

36

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

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

这是从http://groups.google.com/group/xhtml2pdf/browse_thread/thread/4cf4e5e0f4c99f55大量获取的

于 2010-02-01T22:05:50.877 回答
3

HTML 和 Django version=2.0 中的以下代码行对我有用。

<img src="{{company.logo.path}}" height="100px">
于 2018-10-19T05:57:42.367 回答
2
def render_to_pdf( template_src, context_dict):

    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    if page has an image.something:
        pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources)
    else  no image.something :
        pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),result)

    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='examination_report/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))



def fetch_resources(uri, rel):
    if os.sep == '\\': # deal with windows and wrong slashes
        uri2 = os.sep.join(uri.split('/'))
    else:# else, just add the untouched path.
       uri2 = uri

    path = '%s%s' % (settings.SITE_ROOT, uri2)
    return path
于 2012-09-28T17:25:32.687 回答
2

尽管尝试了我在谷歌上找到的所有解决方案,但我无法让图像出现。但是这个软糖对我有用,因为 pisa 的命令行版本可以显示图像:

    from tempfile import mkstemp

    # write html to a temporary file
    # can used NamedTemporaryFile if using python 2.6+
    fid, fname = mkstemp(dir='/tmp')
    f = open(fname, 'w+b')
    f.write(html)
    f.close()


    # now create pdf from the html 
    cmd = 'xhtml2pdf "%s"' % fname
    os.system(cmd)
    os.unlink(fname)

    # get the content of the pdf
    filename = fname+'.pdf'
    pdf = open(filename, 'r')
    content = pdf.read()

    pdf.close()
    os.unlink(pdf.name)

    # return content
    response = HttpResponse(content, mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=draft.pdf'

这适用于图像具有 url 或完整路径名的情况,例如。

<img src="/home/django/project/site_media/css/output/images/logo.jpg" />

<img src="http://www.mysite.com/css/output/images/logo.jpg" />
于 2010-09-14T10:30:09.263 回答
2

以上所有代码都对我不起作用。最后,我通过放置 get_full_path 程序让它工作。所以最终的代码看起来像这样

def render_to_pdf( template_src, context_dict):
    now = datetime.now()
    filename = now.strftime('%Y-%m-%d') + '.pdf'
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),result, path=path)

    if not pdf.err:
      response = HttpResponse(result.getvalue(), mimetype='application/pdf')
      response['Content-Disposition'] = 'attachment; filename="'+filename+'"'
      return response
   return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

def get_full_path_x(request):
    full_path = ('http', ('', 's')[request.is_secure()], '://',
    request.META['HTTP_HOST'], request.path)
    return ''.join(full_path) 
于 2013-04-15T16:31:41.847 回答
1

您也可以将图像转换为 base64。

http://www.motobit.com/util/base64-decoder-encoder.asp

转换为 base64,您将永远不会遇到图像链接问题。

于 2014-03-05T16:12:01.423 回答
0

之后您可以随时使用 IText/ISharp 添加图像。

于 2010-02-02T20:12:18.050 回答