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

17,338

Solution 1

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();

Solution 2

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";
}

Solution 3

var reader = new window.FileReader();
reader.readAsDataURL(doc.output("blob"));
reader.onloadend = function () 
{
    ...
    method: 'POST',
    data: {
        attachment: reader.result
    }
    ...
}
Share:
17,338
nlopez
Author by

nlopez

Updated on July 22, 2022

Comments

  • nlopez
    nlopez almost 2 years

    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!

  • daniel
    daniel over 6 years
    how can I send the filename?
  • Nadim
    Nadim almost 6 years
    JS: data.append('filename', 'thename'); PHP: $filename = $_POST['filename'];
  • Alberto Crespo
    Alberto Crespo over 4 years
    Super nice. For me worked changing data: {data: pdf}, for data: pdf . Thanks
  • Jed
    Jed over 4 years
    Thanks! Been stucked for a couple of days and the btoa conversion did the trick.