Pisa (XHTML -> PDF) in Django will not display images in PDF

萝らか妹 提交于 2019-12-10 06:18:26

问题


To start, I've seen the other threads on this, and I have tried nearly everything to try to fix this but...

When using Pisa to render an HTML page to PDF, the images in said HTML go conspicuously missing. That is to say, when the page is rendered to HTML, everything is just dandy, but when I switch the output to PDF using Pisa, the images disappear.

The most common thing I've found to do is to create a link callback function thus:

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

def my_view(request, variable1):
    html = render_to_string('template_goes_here.html', dict, context_instance=RequestContext(request))
    result = StringIO()
    pdf = pisa.pisaDocument(StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources)
    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='application/pdf')
    return HttpResponse('Pisa hates you! %s' % cgi.escape(html))

However, this does not work. The PDF comes up, great, but the images are absent.

I also read a suggestion on another thread about writing the HTML to mkstemp, converting it to a PDF via command line, and then outputing the HTML, no success there either.

I even tried installing PIL 1.1.16 instead of 1.1.17 because of someone with a similar issue--no dice.

Does anyone have an idea on where I'm going wrong here?


回答1:


It's been a while since I looked at this, but I think you have to use lambda or functools.

e.g.

links = lambda uri, rel: os.path.join(settings.MEDIA_ROOT, 
    uri.replace(settings.MEDIA_URL, ''))


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



回答2:


I think this might help. Windows use of slashes was the culprit in my case. https://stackoverflow.com/a/12644633/1236599



来源:https://stackoverflow.com/questions/7289592/pisa-xhtml-pdf-in-django-will-not-display-images-in-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!