0

I'm working on a project where I need to export some reports about a certain entity, using wkhtmltopdf with an html template that includes some charts from ApexCharts.js. The charts load fine in a rendered html but not in the pdf generated. Here's a sample of what I'm trying to do:

in report.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    </head>
    <body>
        <div id="chart">
        </div>
    </body>
    <script>
      var options = {
        chart: {
            width: '100%',
            type: 'line',
            animations: {
                enabled: false,
            },
        },
        series: [{
            name: 'sales',
            data: [30,40,35,50,49,60,70,91,125]
        }],
        xaxis: {
            categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999]
        }
      }
      
      var chart = new ApexCharts(document.querySelector("#chart"), options);
      
      chart.render();
    </script>
</html>

in views.py

from django.core.files import File
from io import BytesIO
from wkhtmltopdf.views import PDFTemplateResponse
from django.views.generic import View
from django.shortcuts import redirect
from django.urls import reverse_lazy

class GenerateReportView(View):
    filename = "myfile.pdf"
    template_name = "reports/report.html"

    def get(self, request):
        response = PDFTemplateResponse(request=self.request,
                        template=self.template_name,
                        filename=self.filename,
                        context={},
                        show_content_in_browser= False,
                        cmd_options = {
                                    'quiet': None, 
                                    'enable-local-file-access': True,
                                    'encoding': 'utf8',
                                    'no-stop-slow-scripts': True,
                                    'page-size': 'A4',
                                    'javascript-delay': 5000,
                                }
                            )
        
        file = File(BytesIO(response.rendered_content), name="myfile.pdf")
        Report.objects.create(
                file=file,
        )            
        
        return redirect(reverse_lazy("home:home"))

I have tried the following, with no luck:

  1. Using imgkit to pre-convert the chart to an image.

  2. Disabled the animation on the chart.

  3. Changed width and height of the chart.

Farhan
  • 39
  • 5

0 Answers0