Welcome folks today in this blog post we will be exporting raw html
to pdf document in browser using javascript
and php
. We will be using the jspdf
library for this process.
Get Started
In order to get started you need to make an index.php
file and include the jspdf
library cdn as shown below
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> </html> |
Now we need to include the php
code at the very top to export the raw html
to pdf document as shown below
1 2 3 4 5 6 |
<?php $html = "<h1>Hello World</h1>"; $html .= "<p>This is a PDF document generated in the browser using jsPDF and PHP.</p>"; ?> |
As you can see we have the raw
html inside which we have a simple heading
and a paragraph
. And now we need to add the javascript
code to convert this dynamic html
to pdf document.
1 2 3 4 5 6 7 8 9 |
var pdf = new jsPDF(); // add the content to the PDF pdf.fromHTML(<?php echo json_encode($html); ?>, 15, 15, { 'width': 170 }); // download the PDF pdf.save('document.pdf'); |
As you can see we are using the fromHTML()
method to pass the dynamic html
using the php
code. And after that we are saving the pdf document in the browser using the save()
method.