Reportlab + ajax generate pdf in Django

0

I have a problem when generating a pdf in django, I send the data of a template by ajax to the function that the pdf generates, but when I finish processing the data and build the basic pdf it does not send me the pdf.

This is my views

class planillaPDF (View):     header def (self, pdf, batch):         # data_orden = Lote.objects.get (id = order)         date = str (batch.date)         date2 = date.split ('-')         date3 = date2 [2] + '-' + date2 [1] + '-' + date2 [0]

    #se utiliza el logo de deliboo que esta guardado en media/
    archivo_imagen = str(settings.STATICFILES_DIRS[0]) + '/img/logo_deliboo.png'
    #se define el tamano de la imagen a cargar y las coordenadas
    pdf.drawImage(archivo_imagen, 30, 700, 120, 90, preserveAspectRatio=True)
    #dibujamos una cadena en la ubicacion X,Y especificada
    pdf.setFont("Helvetica", 20)
    pdf.drawString(200,680, u"Lote de produccion N°" + str(lote.id))
    pdf.setFont("Helvetica", 14)
    pdf.drawString(250, 663,u"Fecha de emisión " + fecha3)

def post(self, request):
    #se indica el tipo de contenido a devolver, en este caso un pdf
    datos = request.POST
    ddatos_string = list(datos.items())
    ddatos_json = json.loads(ddatos_string[0][0])
    response = HttpResponse(mimetype = 'applicaction/pdf')
    ancho, alto = A4
    #la clase io.BytesIO permite trabajar un array de bytes como fichero binario. se usa como almacenamiento temporal
    buffer = BytesIO()
    #Canvas nos permite hacer el reporte con coordenadas x e Y
    pdf = canvas.Canvas(buffer, pagesize=letter)
    lote = Lote()
    lote.save()
    for dic in ddatos_json:
        prod_lote = Producto_lote()
        intermedio = producto_lote_intermedia()
        producto_lote = producto.objects.get(id = dic['nombre_producto'])
        prod_lote.producto = producto_lote
        if "convenio" in dic.keys() and "pto_venta" in dic.keys() and "cafeteria" in dic.keys():
            prod_lote.convenio = dic['convenio']
            prod_lote.cafeteria = dic['cafeteria']
            prod_lote.pto_venta = dic['pto_venta']
            prod_lote.total = dic['total']
            prod_lote.save()
            intermedio.lote = lote
            intermedio.item=prod_lote
            intermedio.save()

    pdf_name = "Lote_N°" + str(lote.id) + ".pdf"
    response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    # #se llama al metodo cabecera donde estan definidos los datos de la cabecera del reporte
    self.cabecera(pdf, lote)
    # y = 400
    # y2 = 550
    # y3 = 210
    # y4 = 100
    # # self.tabla_productos(pdf,y,orden)       
    #con show page hacemos un corte de pagina para pasar a la siguiente
    pdf.showPage()
    pdf.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

This is my JS function that AJAX uses

function imprimir(){
var datos = []      
// console.log(el[0]);
table= document.getElementById("pedidos");
for (var i = 1; i < table.rows.length; i++){
var aux = {};       
aux['nombre_producto'] = table.rows[i].children[0].id;
aux['convenio'] = table.rows[i].children[1].innerText;          aux['cafeteria'] = table.rows[i].children[2].innerText          aux['pto_venta'] = table.rows[i].children[3].innerText
aux['total'] = table.rows[i].children[4].innerText  
datos.push(aux);
}
// console.log(datos);
var url = "{% url "produccion:reporte_lote_pdf" %}";
$.ajaxSetup({
headers: {"X-CSRFToken": '{{csrf_token}}'}
});
$.ajax({ 
type:'post', 
url:url,
data: JSON.stringify(datos),
dataType: 'json', 
success:function(data){ 
document.location.href='data';  
}
}); 
}
    
asked by DrakeNigth 31.08.2018 в 23:24
source

0 answers