django - "Need a valid file name!"xhtml2pdf 与 Django

标签 django python-3.x xhtml2pdf pisa

我的问题是:我正在使用 xhtml2pdf 库从 html 创建一个 pdf 文件。创建 pdf 文件后,我使用 sendgrid API 通过电子邮件将文件发送给用户。但是,我无法将图像嵌入到 pdf 文件中,因为应用程序返回“需要有效的文件名!”信息。我在几个地方进行了研究,但找不到解决方案。使用的代码如下。

HTML代码:

<img src="/static/media/logo.jpg" alt="Image">

python代码(将html转换为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
mUrl = settings.MEDIA_URL
mRoot = settings.MEDIA_ROOT

# convert URIs to absolute system paths
if uri.startswith(mUrl):
    path = os.path.join(mRoot, uri.replace(mUrl, ""))

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

def render_to_pdf(template_source, context_dict={}):
    from io import BytesIO
    from django.http import HttpResponse
    from django.template.loader import get_template
    from xhtml2pdf import pisa

    template = get_template(template_source)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, 
                        link_callback=link_callback, encoding='UTF-8')

    if not pdf.err:
        return result.getvalue()
    return None

python代码(通过电子邮件发送pdf文件):
def send_mail_template(subject, template_name, context, recipient_list, from_email=<email>, attachments=None):

sg = sendgrid.SendGridAPIClient(apikey=<apikey>)
sendgrid_from_email = Email(email=from_email, name=<name>)
message_html = render_to_string(template_name, context)
content = Content("text/html", message_html)

sendgrid_to_email = Email(recipient_list[0])
mail = Mail(sendgrid_from_email, subject, sendgrid_to_email, content)

try:
    if attachments is not None:
        for attachment in attachments:
            sendgrid_attachment = Attachment()
            sendgrid_attachment.content = base64.b64encode(attachment['file']).decode()
            sendgrid_attachment.content_id = attachment['filename']
            sendgrid_attachment.type = attachment['type']
            sendgrid_attachment.filename = attachment['filename']
            sendgrid_attachment.disposition = attachment['disposition']

            mail.add_attachment(sendgrid_attachment)
except Exception as err:
    print(err)

response = sg.client.mail.send.post(request_body=mail.get())

return response.status_code

错误:
Need a valid file name!
'<img alt="Image" src="/static/media/logo.jpg"/>'

最佳答案

看来xhtml2pdf在渲染位于模板旁边的图像时存在一些问题。为了解决该问题,您可以尝试:

  • 放置静态图像的完整路径,如
  • 将您的图片上传到某个存储桶并在 src 中提供完整网址.
  • 关于django - "Need a valid file name!"xhtml2pdf 与 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53853924/

    相关文章:

    方法中的 Python 局部变量

    python - 如何获取关键字后的字符串

    html - <mark> 将 Html 呈现为 pdf 时,Html 标记不起作用

    javascript - 数据表不显示 Django

    python - Django Stripe InvalidRequestError : Request req_******: Not a valid URL

    mysql - Python3 奇怪的字符和 utf-8 无法删除它

    python - django博客归档、索引和分页综合应用

    Django 到 PostgreSQL : Error loading psycopg2

    python - Django - 使用 xhtml2pdf 将生成的 PDF 保存在模型中