Domanda

Sto usando un esempio standard dal web (http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html) per convertire una vista / modello Django in un PDF.

Esiste un modo "facile" per includere immagini (da un URL o da un riferimento sul server) nel modello in modo che mostreranno sul PDF?

È stato utile?

Soluzione

Ho fatto funzionare le immagini. Il codice è il seguente:

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

Questo è stato preso liberamente da http://groups.google.com/group/xhtml2pdf/browse_thread/thread/4cf4e5e0f4c99f55

Altri suggerimenti

Non riuscivo a far apparire le immagini nonostante ci provassi ogni soluzione che potevo trovare su Google. Ma questo fondente ha funzionato per me come versione della riga di comando di PISA visualizza le immagini 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'

Ciò ha funzionato in cui le immagini avevano un URL o il nome completo, ad es.

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

<img src="http://www.mysite.com/css/output/images/logo.jpg" />
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

Tutto il codice sopra non ha funzionato per me. Alla fine l'ho fatto funzionare mettendo la procedura GET_FULL_PATH. Quindi il codice finale sembra questo

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) 

La riga di codice seguente in HTML e Django versione = 2.0 funziona per me.

<img src="{{company.logo.path}}" height="100px">

Potresti sempre aggiungere le immagini in seguito con Itext/Isharp.

Puoi convertire anche l'immagine in Base64.

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

Convertindo in base64 Non avrai mai problemi con i collegamenti a immagine.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top