b0w3rb0w3r
b0w3rb0w3r

Reputation: 937

Storing generated PDF files on the server

Using the jsPDF plugin, I am creating a .pdf file and generating a download based on a button click. I would like to save the file onto my server instead of initiating the download. So when the button is clicked I would like the file to be saved in :

/tmp/uploads/pdf/example.pdf

I am aware I need have to use Jquery.Ajax to post the file to the server. However, looking at the documentation and I didn't see any support for .pdf as a datatype.

My code:

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

    function html() {
        var doc = new jsPDF('p', 'pt');
        var res = doc.autoTableHtmlToJson(table, true);
        doc.autoTable(res.columns, res.data);
        doc.save( tbl+".pdf");
    }
    html();
});

Based on this xml document saving example I tried the following:

var pdfDocument = doc.save( tbl+".pdf");
        var pdfRequest = $.ajax({
              url: "/tmp/uploads/pdf",
              processData: false,
              data: pdfDocument
            });

This downloaded the file instead of saving it. How can I save the file?

Upvotes: 14

Views: 44517

Answers (5)

varsha dokhale
varsha dokhale

Reputation: 11

I have successfully save jspdf file in server using jspdf, javascript and php with png image

here is the javascript

var doc = btoa(pdf.output());
var data = new FormData();
data.append("data", doc);
var xhr = new XMLHttpRequest();
xhr.open( 'post', 'data/test.php?name=' +name, true );
alert(data);
xhr.send(data);

And the php file

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

Upvotes: 1

Nitin
Nitin

Reputation: 197

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.

Upvotes: 1

mahmoud hemdan
mahmoud hemdan

Reputation: 31

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

Upvotes: 3

Nico
Nico

Reputation: 3542

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

Upvotes: 21

b0w3rb0w3r
b0w3rb0w3r

Reputation: 937

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.

Upvotes: 11

Related Questions