Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

389
Visualizações
Send PDF attached email using JsPDF with ajax and Django python

I have a issue with send pdf attached email using jspdf with ajax and django. The issue is server side views.py print(pdf_s) always retrun 'None' but client side console.log(pdf) returns binary values.

Please refer the below code which i was tried.

script.js

This is client side code. and I'm using Ajax to send data to server

function sendMail(){
    getCanvas().then(function(canvas) {
        console.log('Test');
        var img = canvas.toDataURL("image/png",0.98);
        var imgWidth = 200;
        var pageHeight = 295;
        var imgHeight = canvas.height * imgWidth / canvas.width;
        var heightLeft = imgHeight;

        var doc = new jsPDF('p', 'mm', 'a4', 'pt');
        var position = 0;

        doc.addImage(img, 'JPEG', 5, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            doc.addPage();
            doc.addImage(img, 'JPEG', 5, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;
        }
        var pdf = btoa(doc.output());
        console.log(pdf);
        $.ajax({
            type:'POST',
            url:'sendmail/',
            data:{
                pdf_data: pdf,
                csrfmiddlewaretoken: csrftoken
            },
            success:function(data){
                console.log(data);
            }

        });
    });
}

views.py

def SendMail(request,scan_id):

    pdf_s = request.GET.get('pdf_data')
    print(pdf_s)
    fo = open('test.pdf','w')
    fo.write(pdf_s)
    fo.close()

    html_content = "Test Message"
    email = EmailMessage("test", html_content, "test", ["test@test.com"])
    email.content_subtype = "html"

    fd = open('test.pdf', 'r')
    email.attach('test', fd.read(), 'application/pdf')

    res = email.send()
    if res:
        status = 'Success'
    else:
        status = 'Fail'
    return HttpResponse(status)
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Check ajax request via browser dev tools > network. Perhaps "pdf_data" parameter does not exist.

I send file via native js.

JS

var formData = new FormData();
formData.append('file.pdf', file);
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
    if (xhr.readyState === 4 && xhr.status === 200){
        result=xhr.responseText;
        console.log(result);
    }
}
xhr.open('POST', url, true);
xhr.setRequestHeader("X-CSRFToken", csrfmiddlewaretoken);
xhr.send(formData);

Python

element_file=File(request.FILES[request.FILES.keys()[0]])
with open('file.pdf','wb+') as destination: 
   for chunk in element_file.chunks(): destination.write(chunk)

It's work in case if send file from local computer via input type="file"

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda