【问题标题】:Cant get images to convert to pdf using xhtml2pdf (url of file returning errror)无法使用 html2pdf 将图像转换为 pdf(文件返回错误的 URL)
【发布时间】:2018-09-04 03:23:05
【问题描述】:

这是我找到的假设解决方案。 https://stackoverflow.com/a/2180417

我正在尝试实现它,但我无法做到。

这是我当前的代码:

utils.py

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
     template = get_template(template_src)
     html  = template.render(context_dict)
     result = BytesIO()
     pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources)
     if not pdf.err:
          return HttpResponse(result.getvalue(), content_type='application/pdf')
     return None

def fetch_resources(uri, rel):
    path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

    return path

views.py

 from django.http import HttpResponse
 from django.views.generic import View

 from yourproject.utils import render_to_pdf #created in step 4

 class GeneratePdf(View):
     def get(self, request, *args, **kwargs):
         data = {
              'today': datetime.date.today(), 
              'amount': 39.99,
             'customer_name': 'Cooper Mann',
             'order_id': 1233434,
         }
         pdf = render_to_pdf('pdf/invoice.html', data)
         return HttpResponse(pdf, content_type='application/pdf')

如果我只是渲染一个普通的模板,一切都会正确加载,所以我知道问题出在这部分过程中。 invoice.html 模板包含一个 URL,例如 /home/images/products/1231

<img src='{{ photo.url }}'>

【问题讨论】:

    标签: python django python-3.x python-2.7 xhtml2pdf


    【解决方案1】:

    要在 pdf 中渲染图像,您需要使用以下函数进行图像回调:

    def link_callback(uri, rel):
        """
        Convert HTML URIs to absolute system paths so xhtml2pdf can access those
        resources
        """
        # use short variable names
        sUrl = settings.STATIC_URL      # Typically /static/
        sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
        mUrl = settings.MEDIA_URL       # Typically /static/media/
        mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/
    
        # convert URIs to absolute system paths
        if uri.startswith(mUrl):
            path = os.path.join(mRoot, uri.replace(mUrl, ""))
        elif uri.startswith(sUrl):
            path = os.path.join(sRoot, uri.replace(sUrl, ""))
        else:
            return uri  # handle absolute uri (ie: http://some.tld/foo.png)
    
        # make sure that file exists
        if not os.path.isfile(path):
                raise Exception(
                    'media URI must start with %s or %s' % (sUrl, mUrl)
                )
        return path
    

    接下来添加渲染函数。

    链接:Biblioteca xhtml2pdf

    如果此答案对您有所帮助,请将其标记为答案。

    【讨论】:

    • 它是否返回任何错误?如果是这样,它会显示什么错误?
    • 警告必须是有效的网址
    • 你能在html页面上渲染图片吗?
    【解决方案2】:

    无需设置获取资源。它对我有用

    def render_to_pdf(template_src, context_dict={}):
        template = get_template(template_src)
        html = template.render(context_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
         return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None
    

    也可以试试这个链接html-template-to-pdf-in-django

    【讨论】:

    • 你也在渲染图像吗?我有这个确切的代码,但它不起作用。
    • 如果是这样,您的视图是什么样的?
    • 你的视图是什么样子的
    • 你能参考我给的一个链接吗
    • 兄弟这就是我使用的教程。即使在他的 youtube cmets 中,他也承认没有渲染图像
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 2013-12-21
    • 2022-08-17
    • 2011-09-29
    • 2014-06-13
    相关资源
    最近更新 更多