简体   繁体   English

jsPDF-将pdf发送到服务器最终损坏

[英]jsPDF - send pdf to server ends up corrupted

I generate a pdf with text and images using javascript jsPDF library. 我使用javascript jsPDF库生成包含文本和图像的pdf文件。 Then I want to send the file to server in order to send an email with it. 然后,我想将文件发送到服务器以便随它发送电子邮件。 The problem is that the file that arrives on server is corrupted and can't be opened or I can't see the images on the pdf. 问题是到达服务器的文件已损坏,无法打开,或者我看不到pdf上的图像。

My code: 我的代码:

var pdf = btoa(doc.output()); - this gives an error: Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. -这将产生错误: Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

var pdf = btoa(encodeURIComponent(doc.output()));
var data = new FormData();
data.append("data" , pdf);
var xhr = new XMLHttpRequest();
xhr.open( 'post', '/url', true );
xhr.send(data);

I also tried other things like: 我还尝试了其他方法,例如:

var pdf = btoa(encodeURIComponent(doc.output('blob'))); - the file can't be opened -文件无法打开

var pdf = btoa(doc.output('blob')); - the file can't be opened -文件无法打开

var pdf = btoa(unescape(encodeURIComponent(doc.output()))); - the file will open but the images are some grey lines -文件将打开,但是图像有些灰线

PS: I am using Laravel 5. Server code: PS:我正在使用Laravel5。服务器代​​码:

$data = base64_decode($_POST['data']);
$fname = "test.pdf"; 
$file = fopen("pdf/" .$fname, 'w'); 
fwrite($file, $data); 
fclose($file);

SOLUTION: 解:

js code: js代码:

var blob = doc.output('blob');
var fd = new FormData();
fd.append('data', blob);
$.ajax({
   type: 'POST',
   url: '/url',
   data: fd,
   processData: false,
   contentType: false
}).done(function(data) {
   console.log(data);
});

server code: 服务器代码:

if(!empty($_FILES['data'])){
    move_uploaded_file(
        $_FILES['data']['tmp_name'],
        public_path() . '/test.pdf'
    );
    return "Pdf was successfully saved.";
} else {
    return "No Data Sent";
}

btoa is messed up with the ascii byte range... javascript can't hold all character. btoa弄乱了ascii字节范围... javascript无法容纳所有字符。 That's the reason for why you shouldn't use FileReader's readAsBinaryString either... Handle binary the right way, not as string or ~3x larger base64 string, but as a blob, ArrayBuffer or a typed array and it will turn out fine 这就是为什么您不应该使用FileReader的readAsBinaryString的原因……以正确的方式处理二进制文件,而不是字符串或〜3x较大的base64字符串,而是以blob,ArrayBuffer或类型化数组的形式处理,结果会很好

var blob = doc.output('blob')
xhr.send(blob)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM