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

120
Visualizações
How to convert HTML Application into PDF and send it to Ajax POST call as multipart/form-data

I'm facing an issue in converting my HTML page to pdf and sending to Ajax POST as multipart/form-data.. After checking in many pages, I came to know that using jsPDF plugin we can achieve.

But using jsPDF we have to convert HTML into jpg(in base64 format) and then it can be downloaded to PDF.

But I want to convert into PDF format and that converted PDF needs to be sent to Ajax POST as multipart/form-data.

Below is the code I'm trying with...

<script>
var mywindow = window.open();
mywindow.document.write('<html><head><title>Convert to PDF</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<p>Convert this Page to PDF and send it to Ajax POST as Form</p>');
mywindow.document.write('</body></html>');

html2canvas(mywindow.document.body, {
    onrendered: function(canvas) {
        img = canvas.toDataURL("image/jpeg", 1.0);
        doc = new jsPDF();
        doc.addImage(img, 'JPEG', 0, 0);//This is converting into jpg format in base64 format, But i want base64 in pdf format.
        doc.save('test.pdf'); // This is to save in local system(After getting downloaded, PDF is not displaying properly, It is very clumsy)
        
        var form = new FormData();
        var blob = new Blob([img.split(",")[1]], {
            type: "pdf"
        }); // Here im trying to convert jpg to pdf But that is not working
        form.append("file", blob, "FSM.pdf");
        form.append("fileName", "FSM.pdf");
        form.append("description", "12");
        
        
        
        $.ajax({
            "url": "my_URL",
            "method": "POST",
            "timeout": 0,
            "headers": {
                "Content-Type": "multipart/form-data"
            },
            "processData": false,
            "mimeType": "multipart/form-data",
            "contentType": false,
            "data": form,
            success: function(res) {
                var res;
            },
            error: function(res) {
                console.log(res);
            }
        });
    }
});
</script>

Can someone please help me to resolve my issue? I need to send PDF to Ajax POST as multipart/form-data

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The easiest way for doing this is via a external library like jsPDF and then send the blob data in a Form to the backend similar to submit.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <!-- CDN jsPDF -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
</head>

<body>
  <!-- Button to send AJAX -->
  <button id="btn" onclick="javascript:send()">Send Doc via AJAX</button>
  <script>
    function send() {
      var doc = new jsPDF();
      doc.fromHTML('<h1>Hello World!</h1>', 20, 20);

      var formData = new FormData();
      var blob = new Blob([doc.output("blob")], { type: "application/pdf" });
      formData.append("file", blob, "document.pdf");

      var request = new XMLHttpRequest();
      request.open("POST", "/upload");
      request.send(formData);
    }
  </script>
</html>

I am not sure the printWindow has any API to do the above.

about 4 years ago · Juan Pablo Isaza Relatório

0

I think you should convert the image to base64 and then to Blob and send it to the server. When you use base64 images, a lot of lines will be sent to server. With blob, it's only the file.

You can use this code bellow:

function dataURLtoBlob(dataURL) {
  let array, binary, i, len;
  binary = atob(dataURL.split(',')[1]);
  array = [];
  i = 0;
  len = binary.length;
  while (i < len) {
    array.push(binary.charCodeAt(i));
    i++;
  }
  return new Blob([new Uint8Array(array)], {
    type: 'image/png'
  });
};

And canvas code here:


const file = dataURLtoBlob( canvas.toDataURL("image/jpeg", 1.0) );

After that you can use ajax with Form:

const fd = new FormData;

fd.append('image', file);

$.ajax({
  type: 'POST',
  url: '/url-to-save',
  data: fd,
  processData: false,
  contentType: false
});
about 4 years ago · Juan Pablo Isaza 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