Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
6.0 kB
1
Indexable
Never
from io import BytesIO
from django.shortcuts import render
from flask import get_template_attribute
from appmanager.models import Table, CategoryTable, Fields
from django.http import FileResponse, JsonResponse, HttpResponse
from django.core.paginator import Paginator
from django_plotly_dash import DjangoDash
import dash_html_components as html
import dash_core_components as dcc
from django.template.loader import render_to_string
from xhtml2pdf import pisa
from django.template.loader import get_template
# from weasyprint import HTML
import base64
from django.conf import settings
from plotly.graph_objs import Figure
from io import BytesIO
from plotly.offline import plot
import plotly.graph_objs as go
import plotly.io as pio
# import tempfile
import os
import random
from django.templatetags.static import static
from plotly.subplots import make_subplots
import string
from datetime import datetime



def render_to_pdf(template_src, context_dict={}):
	template = get_template(template_src)
	html  = template.render(context_dict)
	result = BytesIO()
	pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
	if not pdf.err:
		return HttpResponse(result.getvalue(), content_type='application/pdf')
	return None


data = {
	"company": "Dennnis Ivanov Company",
	"address": "123 Street name",
	"city": "Vancouver",
	"state": "WA",
	"zipcode": "98663",


	"phone": "555-555-2345",
	"email": "youremail@dennisivy.com",
	"website": "dennisivy.com",
}



def generate_random_filename(length=15):
    letters = string.ascii_letters
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    random_string = ''.join(random.choice(letters) for _ in range(length))
    return f"{timestamp}_{random_string}.png"

def create_figure1():
    # Create Figure 1
    fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])])
    fig.update_layout(title='Figure 1')
    return fig

def create_figure2():
    # Create Figure 2
    fig = make_subplots(rows=1, cols=2)
    fig.add_trace(go.Scatter(x=[1, 2, 3], y=[2, 4, 5], name='SF'), row=1, col=1)
    fig.add_trace(go.Scatter(x=[1, 2, 3], y=[5, 3, 1], name='Montreal'), row=1, col=2)
    fig.update_layout(title='Figure 2')
    return fig

def create_figure3():
    # Create Figure 3 - Pie Chart
    labels = ['Label 1', 'Label 2', 'Label 3']
    values = [45, 30, 25]

    fig = go.Figure(data=[go.Pie(labels=labels, values=values)])

    fig.update_layout(title='Figure 3 - Pie Chart')

    return fig

def create_figure4(value):
    # Create Gauge Chart
    fig = go.Figure(
        go.Indicator(
            mode="gauge+number",
            value=value,
            domain={"x": [0, 1], "y": [0, 1]},
            gauge=dict(
                axis=dict(range=[None, 100]),
                bar=dict(color="darkblue"),
                steps=[
                    {"range": [0, 50], "color": "green"},
                    {"range": [50, 80], "color": "orange"},
                    {"range": [80, 100], "color": "red"},
                ],
            ),
        )
    )
    fig.update_layout(title='Fig 4 - Jauge de vie')
    return fig

def create_figure5():
    # Create Choropleth Map
    data = [
        dict(
            type='choropleth',
            locations=['USA', 'CAN', 'MEX'],
            z=[100, 200, 300],
            text=['United States', 'Canada', 'Mexico'],
            colorscale='Viridis',
            autocolorscale=False,
            reversescale=True,
            marker=dict(
                line=dict(
                    color='rgb(180,180,180)',
                    width=0.5
                )),
            colorbar=dict(
                dtick=10,  # Replace 'autotick' with 'dtick'
                tickprefix='',
                title='Value'
            ),
        )
    ]

    layout = dict(
        title='Fig 5 - Choropleth Map',
        geo=dict(
            showframe=False,
            showcoastlines=False,
            projection=dict(
                type='mercator'
            )
        )
    )

    fig = go.Figure(data=data, layout=layout)
    return fig
    
def save_figure(fig, file_path):
    # Save the figure as a PNG file
    pio.write_image(fig, file_path)

def download_charts_pdf(request):
    # Gets the value from template 
    if request.method == 'GET':
        gaugevalue = int(request.GET.get('gaugevalue'))
    else:
        gaugevalue = 10
    # Generate the figures
    fig1 = create_figure1()
    fig2 = create_figure2()
    fig3 = create_figure3()
    fig5 = create_figure5()
    fig4 = create_figure4(gaugevalue)

    # Save the figures as PNG files
    filename1 = generate_random_filename()
    filename2 = generate_random_filename()
    filename3 = generate_random_filename()
    filename4 = generate_random_filename()
    filename5 = generate_random_filename()

    file_path1 = os.path.join(settings.MEDIA_ROOT, 'charts', filename1)
    file_path2 = os.path.join(settings.MEDIA_ROOT, 'charts', filename2)
    file_path3 = os.path.join(settings.MEDIA_ROOT, 'charts', filename3)
    file_path4 = os.path.join(settings.MEDIA_ROOT, 'charts', filename4)
    file_path5 = os.path.join(settings.MEDIA_ROOT, 'charts', filename5)
    save_figure(fig1, file_path1)
    save_figure(fig2, file_path2)
    save_figure(fig3, file_path3)
    save_figure(fig4, file_path4)
    save_figure(fig5, file_path5)

    context = {
        "data":data,
        "file_path1":file_path1,
        "file_path2":file_path2,
        "file_path3":file_path3,
        "file_path4":file_path4,
        "file_path5":file_path5,
    }

    pdf = render_to_pdf('database/chartdash.html', context)
    response = HttpResponse(pdf, content_type='application/pdf')
    filename = "reports_%s.pdf" %("12341231")
    content = "attachment; filename=%s" %(filename)
    response['Content-Disposition'] = content
    return response