Welcome folks today in this blog post we will be encoding the pdf document to base64 string url in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to include the jspdf
library cdn as shown below
1 2 3 4 5 6 7 8 9 |
<!doctype> <html> <head> <title>jsPDF Convert PDF to Base64 String</title> <script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> </head> <body> </body> </html> |
Now we need to add the anchor tag where we will be adding the href
to encode the pdf to base64 url
1 |
<a href="javascript:demo1()">Encode PDF</a> |
Now we need to write the javascript code where we need to execute the demo1()
function as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function demo1() { var doc = new jsPDF() doc.addPage(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); // Making Data URI var out = doc.output(); var url = 'data:application/pdf;base64,' + btoa(out); var iframe = "<iframe width='100%' height='100%' src='" + url + "'></iframe>" var x = window.open(); x.document.open(); x.document.write(iframe); x.document.close(); document.location.href = url; } |
As you can see we are making the new constructor of jsPDF()
and then we are adding the new page to the pdf document. And then we are adding the text to the pdf document. And then we are encoding the pdf document using the output()
method and after that we are displaying it inside the iframe
tag in browser.