我在将HTML页面转换为pdf并将其作为multipart/form-data
发送到Ajax
POST时遇到问题。。在查看了许多页面后,我知道使用jsPDF
插件我们可以实现。
但使用jsPDF
,我们必须将HTML
转换为jpg(base64格式),然后才能将其下载为PDF。
但我想转换成PDF格式,转换后的PDF需要作为multipart/form-data
发送到Ajax
POST。
下面是我正在尝试使用的代码。。。
<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>
有人能帮我解决我的问题吗?我需要将PDF作为multipart/form-data
发送到Ajax
POST
最简单的方法是通过像jsPDF这样的外部库,然后将表单中的blob数据发送到后端,类似于提交。
<!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>
我不确定printWindow是否有任何API来完成上述操作。
我认为应该将图像转换为base64,然后转换为Blob,并将其发送到服务器。当您使用base64图像时,许多行将被发送到服务器。对于blob,它只是文件。
您可以使用以下代码:
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'
});
};
这里的画布代码:
const file = dataURLtoBlob( canvas.toDataURL("image/jpeg", 1.0) );
之后,您可以将ajax与Form:一起使用
const fd = new FormData;
fd.append('image', file);
$.ajax({
type: 'POST',
url: '/url-to-save',
data: fd,
processData: false,
contentType: false
});