【问题标题】:Django-Weasyprint image issueDjango-Weasyprint 图像问题
【发布时间】:2013-10-07 21:48:27
【问题描述】:

正如文档页面中所说,我在我的 html 文件中定义了一个 img 标记,如下所示:

<img src='{% static 'image.png' %}'/>

这个url存在于服务器中,我什至用http响应做了一个不同的视图,图像显示得很好。这是两个视图的代码:

pdf-weasyprint 视图:

def card_view(request):
    template = loader.get_template('card.html')
    context = {'sample': None
               }
    html = template.render(RequestContext(request, context))
    response = HttpResponse(mimetype='application/pdf')
    HTML(string=html).write_pdf(response)
    return response

html 视图:

def card_view2(request):
    context = {'sample': None,
               }
    return render_to_response('card.html', context, 
                              context_instance=RequestContext(request))

我认为默认的 url fetcher 应该找到并渲染图像(它是 png - 所以不应该涉及格式问题) 有任何想法吗?任何帮助将不胜感激!

【问题讨论】:

    标签: django pdf django-templates pdf-generation weasyprint


    【解决方案1】:

    究竟是什么问题?你在日志中得到什么吗? (如果您的服务器没有记录标准错误,您可能需要configure logging。)生成的 HTML 是什么样的?

    我确实需要上述问题的答案来确认,但我的猜测是图像的 URL 是相对的,但是 HTML(string=...) WeasyPrint 不知道什么是基本 URL。尝试这样的事情。 (我不确定 Django 的详细信息。)

    HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response)
    

    这将在您的应用上发出真正的 HTTP 请求,这可能会在单线程服务器上死锁。 (我认为开发服务器默认为单线程。)

    为避免这种情况以及通过网络的成本,您可能需要考虑编写自定义"URL fetcher"。它可以是任何地方,从专门的图像到仅这一个图像,再到完整的 Django 等价物 Flask-WeasyPrint

    【讨论】:

    • 添加 base_url=request.build_absolute_uri() 完全修复了它。开发服务器很好地处理了请求!谢谢你们的快速响应!!!!很棒的应用;)
    【解决方案2】:

    这里是一个 URL fetcher,它在本地读取(图像)文件,而不执行 HTTP 请求:

    from weasyprint import HTML, CSS, default_url_fetcher
    import mimetypes
    
    def weasyprint_local_fetcher(url):
        if url.startswith('local://'):
            filepath = url[8:]
            with open(filepath, 'rb') as f:
                file_data = f.read()
            return {
                'string': file_data,
                'mime_type': mimetypes.guess_type(filepath)[0],
            }
        return default_url_fetcher(url)
    

    为了使用它,请在您的 URL 中使用 local:// 方案,例如:

    <img src="local://myapp/static/images/image.svg" />
    

    然后,将 fetcher 传递给 HTML __init__ 方法:

    html = HTML(
        string=html_string,
        url_fetcher=weasyprint_local_fetcher,
    )
    

    【讨论】:

    • 只有这个解决方案对我有帮助。谢谢!
    猜你喜欢
    • 2018-12-19
    • 2020-09-03
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2021-02-12
    • 2018-04-06
    • 2020-04-08
    相关资源
    最近更新 更多