0

I am uploading a pdf file generated by jsPDF to the php server. What I am missing here? How can I check the pdf file content before sending it?

In JS,

var doc = new jsPDF(parameters);
    doc.addHTML($('#test')[0], 0, 0, {
}, function() {
    pdf = doc.output('blob');
});

 $.ajax({
            url: 'upload.php',
            type: 'post',
            data: {data: pdf},
            processData: false,
 }).done(function (data) { 
       alert(data);
 }).fail(function (xhr, status, err) { 
       alert(err);
 });

And in php,

<?php
if(!empty($_POST['data'])){
    $data = base64_decode($_POST['data']);
    file_put_contents( "tmp/test.pdf", $data);
 else {
     echo "error";
 }
?>
Gene9y
  • 789
  • 1
  • 11
  • 26
  • _"What I am missing here?"_ - You tell us. Does it work? What do you mean by "check the PDF file"? Validate it to see if it's a valid PDF? – M. Eriksson Feb 16 '18 at 06:51
  • It doesn't work. Just getting the 'error' return. Yes, how can I check the pdf content before uploading it? doc.save() works fine but it seems the pdf is empty or not generated property. – Gene9y Feb 16 '18 at 06:53
  • What happens if you do `console.log(pdf)` right before your ajax? Does `doc.output()` return the correct data? – M. Eriksson Feb 16 '18 at 06:55
  • alert(pdf) shows 'undefined'. So I guess the pdf is not generated inside the function. – Gene9y Feb 16 '18 at 06:58
  • Try the syntax from this answer: https://stackoverflow.com/questions/28193487/how-to-use-addhtml-function-in-jspdf. Actually, the method `addHTML` seem to be deprecated: http://rawgit.com/MrRio/jsPDF/master/docs/global.html#addHTML – M. Eriksson Feb 16 '18 at 07:01
  • Deprecated but in terms of saving a pdf using doc.save(), it works. So it should work to assign the pdf to a variable. – Gene9y Feb 16 '18 at 07:10
  • it seems the variable pdf is only local to the function. So alert shows 'undefined'. Any clue about how to pass the pdf to the outside of the function? – Gene9y Feb 16 '18 at 07:22
  • Two options: 1. Put your ajax code in the callback for `addHTML()`. 2. Make a new function with your ajax code which takes the pdf as an argument and call that function from the callback. `addHTML()` is most likely building the PDF asynchronously, which mean that in your current code, when your ajax is executed, that callback hasn't even been triggered yet. – M. Eriksson Feb 16 '18 at 08:45
  • Took the first option and changed a bit. Works well. Many thanks. – Gene9y Feb 16 '18 at 10:03

0 Answers0