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
2
Answers
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:
And canvas code here:
After that you can use ajax with Form:
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.
I am not sure the printWindow has any API to do the above.