Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to upload pdf to server from ajax data send (using jsPDF)

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!

like image 262
nlopez Avatar asked Jun 18 '15 14:06

nlopez


3 Answers

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();
like image 108
nlopez Avatar answered Sep 17 '22 17:09

nlopez


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";
}
like image 34
Suwarnakumar Kanapathipillai Avatar answered Sep 16 '22 17:09

Suwarnakumar Kanapathipillai


var reader = new window.FileReader();
reader.readAsDataURL(doc.output("blob"));
reader.onloadend = function () 
{
    ...
    method: 'POST',
    data: {
        attachment: reader.result
    }
    ...
}
like image 32
Alexandr Sulimov Avatar answered Sep 18 '22 17:09

Alexandr Sulimov