Search code examples
jqueryajaxpdfjspdf

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?


Solution

  • 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.