Django中的图像未转换为基64

2024-07-07 07:55:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将HTML网页转换为PDF我正在使用Xhtml2pdf库进行此操作,这不会在PDF上显示图像,因此,需要转换可以在PDF上显示的base 64中的图像,我已经编写了Base64,并在图像上应用了我的自定义过滤器,但没有在Base64中转换它,因为图像在生成的PDF中不可见。我做错了什么以下是我的代码:

view.py

class Instagram_Report_View(TemplateView):

    template_name = "Target_Management_System/InstagramPerson_Target_Report.html"
    def get(self, request, *args, **kwargs):
            object_gtr_id = kwargs['object_gtr_id']
            profile = acq.get_data_response_object_by_gtr_id(ObjectId(object_gtr_id))
            print(profile.to_mongo())
            #return render(request, 'Reports_Management_Unit/pdf_file.html',{'profile':profile})
            pdf=render_to_pdf('Reports_Management_Unit/pdf_file.html')
            return pdf

custom_filter.py(在该文件中写入了镜像到base 64的代码)

from django import template
import base64
from io import StringIO
import urllib.request
import requests
register=template.Library()

@register.filter
def convert_to_base64(url):
    
    
    return base64.b64encode(requests.get(url).content)

pdf_file.html

{% load staticfiles %}
{% load custom_filter %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    

</head>

<body>
<img src="{% static 'Reports_Management_Unit/img/profile_pic.jpg' | convert_to_base64 %}">

</body>
</html>




Tags: to图像importidgetobjectpdfrequest