【问题标题】:Convert html to pdf using xhtml2pdf, images not displayed使用 xhtml2pdf 将 html 转换为 pdf,图像不显示
【发布时间】:2013-07-03 03:40:58
【问题描述】:
def create_pdf(pdf_data):
    filename = app.config['UPLOAD_FOLDER'] + "/file.pdf"
    f = file(filename, "wb")
    pdf = pisa.CreatePDF(StringIO(pdf_data.encode('utf-8')), f)
    return pdf

pdf = create_pdf(render_template('receipt.htm', entry=entry, filename=filename))

html模板显示图片,但是使用xhtml2pdf转换成pdf时,图片不显示!

【问题讨论】:

  • 你能显示你的html代码吗?

标签: python flask pisa xhtml2pdf


【解决方案1】:

我认为这对你有用:

def fetch_resources(uri, rel):
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.LOADING_STATIC_FOR_PDF,uri.replace(settings.STATIC_URL, ""))
    return path

def preview_pdf(request):
    context = RequestContext(request)
    if request.method == 'GET':
        context = {
            # sending data to html 
        }
        rendered_html = render_to_string("path/xxx.html", locals())
        template = get_template('path/xxx.html')
        html = template.render(context)
        result = StringIO.StringIO()
        file = open('test.pdf', "w+b")
        pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8',link_callback=fetch_resources)
        file.seek(0)
        pdf = file.read()
        file.close()
        return HttpResponse(pdf, 'application/pdf')

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2019-07-01
    • 2014-08-28
    • 1970-01-01
    相关资源
    最近更新 更多