I'm using jsPDF to generate a pdf on client-side. With the function doc.save('filename.pdf') I can download it. Now I need to save it on the server, so I'm sending the pdf data with .ajax() and receiving it with a PHP script but the images on the generated pdfURL doesn't show (http://mydomain/tmp/test.pdf); only shows the text.
Can you give me a hand please?
My js code:
//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);
});
The 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 the pdf generated after the php scripting proccess: http://control.edge-cdn.com.ar/tmp/test.pdf
And this is the generated with the doc.save() function: http://control.edge-cdn.com.ar/repo/all.pdf Regards!
SOLUTION:
I was trying to send the pdf data as binary. I just base64 encode the string, send it and them decode that on the 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();
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";
}
var reader = new window.FileReader();
reader.readAsDataURL(doc.output("blob"));
reader.onloadend = function ()
{
...
method: 'POST',
data: {
attachment: reader.result
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With