django - pisa : adding images to PDF output

前端 未结 7 1030
醉酒成梦
醉酒成梦 2020-11-28 06:50

I\'m using a standard example from the web (http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html) to convert a django view / template into a PDF.

7条回答
  •  甜味超标
    2020-11-28 07:15

    I could not get images to appear despite trying every solution I could find on google. But this fudge worked for me as the command line version of pisa displays images 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'
    

    This worked where the images had either a url or the full path name, eg.

    
    
    
    

提交回复
热议问题