django pdf with logo image

时间:2012-07-10 10:06:33

标签: django

我使用pisa创建了Invoice Pdf文本模板。但我想在pdf文件中显示徽标(图像)以及文本。我不知道如何以PDF格式显示图像。我的观点如下:

def generate_invoice(request, user_id = None):
    personal_html = ''
    personal_html += 'hai'

    fileread = str(settings.TEMPLATE_DIRS[0])+str('/invoice.html')
    fr = open(fileread, "r").read()
    fr = fr.replace('personal_details', personal_html)
    result = StringIO.StringIO()
    pdf = pisa.CreatePDF(
                        fr,result
                        )
    filewrite = str(settings.TEMPLATE_DIRS[0]) + str('/invoice_write.html')
    empty = ""
    fw = open(filewrite, 'w')
    fw.write(empty)
    fw.write(fr)
    fw.close()
    PaymentPdf.objects.filter(invoicepdf = user_id).delete()
    pdf_contents     = render_to_pdf1('invoice_write.html',result)
    file_to_be_saved = ContentFile(pdf_contents)
    random_str       = ''.join(random.sample((string.ascii_lowercase + string.ascii_uppercase + string.digits), 8))
    resume_name      = (str(user_id) + "_" + random_str + ".pdf").replace("@", '')
    resume           = PaymentPdf.objects.create(name = resume_name, invoicepdf_id = user_id, created_by = request.user)
    resume.name.save(resume_name ,file_to_be_saved)
    file_path = PaymentPdf.objects.get(invoicepdf = user_id).name
    pdf_file = str(file_path).split("media")[1]
    return HttpResponseRedirect('/site_media' + pdf_file)

def render_to_pdf1(template_src, context_dict):
    template = get_template(template_src)
    context  = Context(context_dict)
    html     = template.render(context)
    result   = StringIO.StringIO()
    pdf      = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    return result.getvalue()

有人帮我用pdf显示图片吗?

2 个答案:

答案 0 :(得分:3)

参考Pisa (XHTML -> PDF) in Django will not display images in PDF,然后添加

links    = lambda uri, rel: os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ''))
pdf      = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),dest=result, link_callback=links)

在视图的render_to_pdf1中, 并在html中:

<img src="/site_media/img/logo.jpg"/ height="55" width="275">

它会起作用。

答案 1 :(得分:0)

我认为 html 包含这样的内容:

<img src="/media/xxx.jpg"/>

比萨需要这样的东西:

<img src="http://mydomain.foo/media/xxx.jpg"/>