How to upload PDF to server from ajax data send (using jsPDF)

I am using jsPDF to create a client side pdf file. Using the doc.save ('filename.pdf') function, I can load it. Now I need to save it on the server, so I send the data in pdf format using .ajax () and get it using the PHP script, but the images on the generated pdfURL are not displayed ( http: //mydomain/tmp/test.pdf ); only text is displayed.

Can you give me a hand?

My js code is:

//doc.save('test.pdf'); WORKS WELL var pdf = doc.output(); $.ajax({ method: "POST", url: "inc/test.php", data: {data: pdf}, }).done(function(data){ console.log(data); }); 

PHP script:

 <?php if(!empty($_POST['data'])){ $data = $_POST['data']; print_r($data); file_put_contents( "../tmp/test.pdf", $data ); } else { echo "No Data Sent"; } exit(); ?> 

This is a pdf file created after the php scripting process: http://control.edge-cdn.com.ar/tmp/test.pdf

And this is generated using the doc.save () function: http://control.edge-cdn.com.ar/repo/all.pdf Hello!

+5
source share
3 answers

SOLUTION :

I tried to send pdf data as binary. I just base64 encode the string, send it and decode that in php.

JS:

  var pdf = btoa(doc.output()); $.ajax({ method: "POST", url: "inc/test.php", data: {data: pdf}, }).done(function(data){ console.log(data); }); 

PHP:

 if(!empty($_POST['data'])){ $data = base64_decode($_POST['data']); // print_r($data); file_put_contents( "../tmp/test.pdf", $data ); } else { echo "No Data Sent"; } exit(); 
+9
source
 var reader = new window.FileReader(); reader.readAsDataURL(doc.output("blob")); reader.onloadend = function () { ... method: 'POST', data: { attachment: reader.result } ... } 
0
source

Js

 var pdf =doc.output(); var data = new FormData(); data.append("data" , pdf); var xhr = new XMLHttpRequest(); xhr.open( 'post', 'inc/test.php', true ); xhr.send(data); 

Php

 if(!empty($_POST['data'])){ $data = $_POST['data']; $fname = "test.pdf"; $file = fopen("test/pdf/" .$fname, 'r'); fwrite($file, $data); fclose($file); } else { echo "No Data Sent"; } 
0
source

All Articles