Storing generated PDF files on the server

I managed to fix this using FormData(), here's how I did it:

$(document).on("click", "#PDF", function () {
    var table = document.getElementById("result");
    var cols = [],
        data = [];

    function html() {
        var doc = new jsPDF('p', 'pt');
        var res = doc.autoTableHtmlToJson(table, true);
        doc.autoTable(res.columns, res.data);
        var pdf =doc.output(); //returns raw body of resulting PDF returned as a string as per the plugin documentation.
        var data = new FormData();
        data.append("data" , pdf);
        var xhr = new XMLHttpRequest();
        xhr.open( 'post', 'upload.php', true ); //Post to php Script to save to server
        xhr.send(data);

    }
    html();
});

upload.php

if(!empty($_POST['data'])){
    $data = $_POST['data'];
    $fname = "test.pdf"; // name the file
    $file = fopen("testa/pdf/" .$fname, 'w'); // open the file path
    fwrite($file, $data); //save data
    fclose($file);
} else {
    echo "No Data Sent";
}

The key part being var pdf =doc.output(); where you want to get the raw pdf data.


Using Asp.net/C# and jQuery: Based on @mahmoud hemdan answer, i did for my requirement. I did like below:

Javascript:

function createPDF(){
  var doc = new jsPDF('landscape');
  var u = $("#myCanvas").toDataURL("image/png", 1.0);
  doc.addImage(u, 'JPEG', 20, 20, 250, 150);
  var base64pdf = btoa(doc.output());
  $.ajax({
      url: 'ChartPDF.aspx?pdfinput=1',
      type: 'post',
      async: false,
      contentType: 'application/json; charset=utf-8',
      data: base64pdf,
      dataType: 'json'
  });
}

ChartPDF.aspx.cs code:

protected void Page_Load(object sender, EventArgs e)
    {
        var pdfinput= Request.QueryString["pdfinput"];
        if (pdfinput!= null)
        {
            var jsonString = string.Empty;
            HttpContext.Current.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            var byteArray = Convert.FromBase64String(jsonString);
            //Get your desired path for saving file
            File.WriteAllBytes(@"C:\ReportPDFs\Test.pdf", byteArray);
        }
    }

I called up the page without any querystring parameter and the page creates the graph(Code not given for drawing the graph as it is not part of the qs.) and after that it calles createPDF() function which result in reloading the page and saving the graph as pdf file on server. Later i use the file from path.


If your PDF contains binary data, you can get into problems if you try to transfer the PDF via string. I used the blob output format of jsPDF with success.

var doc = new jsPDF();
// ... generate pdf here ...

// output as blob
var pdf = doc.output('blob');

var data = new FormData();
data.append('data' , pdf);

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (this.readyState == 4) {
    if (this.status !== 200) {
      // handle error
    }
  }
}

xhr.open('POST', 'upload.php', true);
xhr.send(data);

Your upload.php can then use the $_FILES array in PHP

<?php
if(!empty($_FILES['data'])) {
    // PDF is located at $_FILES['data']['tmp_name']
    // rename(...) it or send via email etc.
    $content = file_get_contents($_FILES['data']['tmp_name']);
} else {
    throw new Exception("no data");
}
?>

javascript

doc = new jsPDF({
         unit: 'px',
         format: 'a4'
     });
    doc.addImage(img, 'JPEG', 20, 20);
    var data = {};
    var base64pdf = btoa(doc.output());
    $.ajax({
        url: 'WS/FileUploadHandler.ashx',
        type: 'post',
        async: false,
        contentType: 'application/json; charset=utf-8',
        data: base64pdf,
        dataType: 'json'
    });

FileUploadHandler.ashx

public void ProcessRequest(HttpContext context)
    {
        var jsonString = String.Empty;
        context.Request.InputStream.Position = 0;
        using (var inputStream = new StreamReader(context.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        var byteArray = Convert.FromBase64String(jsonString);
        File.WriteAllBytes(@"C:\Users\mahmoud.hemdan\Downloads\testtest.pdf", byteArray);
    }