Clint_A
Clint_A

Reputation: 536

JS AJAX to post generated file as PDF to server directory

I have a complex table generated via javascript that I'd like to save as PDF on the server. I've looked around at the pdf generation libraries and they all seem to be limited in terms of style, fonts, etc (that's what I meant by 'complex'). The table can be download client side as PDF or printed.

Let's say my function that generates the form to be printed is reportBody(data); - is there a way I can use AJAX to send the document as PDF to a php file that will save it server-side instead of downloading it client-side? The reportBody(data) is a collection of other variables, function calls etc.

So basically the question is - since we can generate a PDF file client-side, can we POST it (the pdf) via ajax to the server?

Upvotes: 1

Views: 1179

Answers (2)

Metabolic
Metabolic

Reputation: 2904

Short answer is Yes. Your provided information is still limited as it's not clear what is ran in the reporBody(data) but most PDF libraries on client side are able to give you the PDF file as base64 encoded data in form of a string. You can then simply send that string to the server and save that as a PDF file. A simple implementation will be something like this:

// I have used jQuery for convenience but you can use any lib or Vanilla JS         
var saveData = $.ajax({
          type: 'POST',
          url: "url-to-the-php-script",
          data: { pdfData: 'base64StringDataHere'},
          dataType: "JSON",
          success: function(resultData) { alert("Save Complete") }
    });

Then on server side, do something like this:

$pdfData= $_POST['pdfData'];    
file_put_contents('filename.pdf', base64_decode($pdfData));

Upvotes: 2

Emeeus
Emeeus

Reputation: 5250

Yes, there are a lot of ways. One would be, if you have html code in your reportBody(data); you could:

  • Send the html to a php file via ajax
  • in this php you could use https://wkhtmltopdf.org/ to generate a pdf file
  • In the client side you could point to that pdf generated

Upvotes: 1

Related Questions