Search code examples
pythondjangodjango-rest-frameworkweasyprintdjango-weasyprint

generate PDF with picture Django rest framework


With the code below, I can easily generate a 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

However, even though I can design the PDF with inline CSS and CSS files, I can't figure out how to insert any photos or pictures into it... Is it even possible to add a picture/logo to a PDF? If so, how may I approach it?


Solution

  • 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