Генерация PDF с помощью картинки Django rest framework

С помощью приведенного ниже кода я могу легко сгенерировать PDF:

import weasyprint

def admin_order_pdf(request, sell_id):  # working fine 
   try:
      sell = Sell.objects.get(id=sell_id)
   except Sell.DoesNotExist:
      return HttpResponse('Sell object does not exist')

   html = render_to_string('sell_invoice.html', {'sell': sell})
   response = HttpResponse(content_type='application/pdf')

   app_static_dir = os.path.join(settings.BASE_DIR, 'pdf', 'static')

   css_path = os.path.join(app_static_dir, 'css', 'css.css')

   response['Content-Disposition'] = f'filename=sell_{sell.id}.pdf'

   weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(css_path)])

   return response

Однако, несмотря на то, что я могу оформить PDF с помощью встроенных CSS и CSS-файлов, я не могу понять, как вставить в него фотографии или картинки... Возможно ли вообще добавить картинку/логотип в PDF? Если да, то как это сделать?

Вы можете легко передавать закодированные данные, используя логотип Python get.

def get_logo_base64_encoded_data():
    logo_path = os.path.join(settings.BASE_DIR, 'pdf', 'static', 'logo', 'logo.png')
    with open(logo_path, 'rb') as f:
        logo_data = f.read()
    return base64.b64encode(logo_data).decode()

def admin_order_pdf(request, sell_id):
    try:
        sell = Sell.objects.get(id=sell_id)
    except Sell.DoesNotExist:
        return HttpResponse('Sell object does not exist')

    html = render_to_string('sell_invoice.html', {'sell': sell, 'logo_base64_encoded_data': get_logo_base64_encoded_data()})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename=sell_{sell.id}.pdf'

   
    weasyprint.HTML(string=html).write_pdf(response)

    return response
Вернуться на верх