2010-02-01 54 views
30

我正在使用網上的標準示例(http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html)將django視圖/模板轉換爲PDF。django - 比薩:將圖像添加到PDF輸出

是否有一種「簡單」的方式在模板中包含圖像(無論是從服務器上的URL還是參考),以便它們顯示在PDF上?

+2

鏈接死了 - 這是它:http://20seven.org/journal/2008/11/11/pdf-generation-with-pisa-in-django/ – Gady 2013-08-29 20:56:05

回答

32

我得到了圖像的工作。代碼如下:

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

+0

fyi對於非Django用戶,'MEDIA_ROOT'是您要轉換的html文檔的目錄在物理位置,而「MEDIA_URL」是該位置的* http友好*版本(例如,對於本地html文件:'MEDIA_URL ='file:///'+ MEDIA_ROOT') 。否則這是一個很好的通用解決方案! – ecoe 2014-07-21 17:30:35

0

你總是可以使用的iText/ISharp事後添加的圖像。

2

儘管嘗試了我可以在Google上找到的每個解決方案,但仍無法獲取圖像。但這種軟糖工作對我來說是比薩的命令行版本顯示圖像OK:

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" /> 
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 
1

所有上面的代碼中並沒有爲我工作。最後,我通過放置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)