Welcome folks today in this blog post we will be using the pdfjs-dist
library to add base64 image as watermark
in pdf document using easypdf-io
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to include the cdn
of the pdf-dist
library and also including the easypdf-io
library cdn as shown below inside the index.html
file as shown below
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<html> <head> <!-- Only include when rendering is required --> <script src="https://unpkg.com/pdfjs-dist/build/pdf.min.js"></script> <script src="https://unpkg.com/pdfjs-dist/build/pdf.worker.min.js"></script> <script src="https://unpkg.com/easypdf-io/dist/easypdf-io.min.js"></script> <!-- Include pdfjs version 2.3.200 for Internet Explorer compatibility, no worker required --> <!-- <script src="https://unpkg.com/pdfjs-dist@2.3.200/build/pdf.min.js"></script> --> </head> <style> #pdf { text-align: center; } #pdf canvas { border: 1px solid black; width: 95%; } </style> <body> <button onclick="createPDF()">Create PDF</button> <button onclick="downloadPDF()">Download PDF</button> <button onclick="renderPDF()">Render PDF</button> <p>PDF as base64 (click create pdf): <small id="pdfBase64"></small> </p> <div id="pdf"></div> </body> <script> function createPDF() { var data = getSampleData(); console.log(data) easypdf.create(data, function(result) { console.log(result); document.getElementById('pdfBase64').innerText = result.pdf; /* console.log(result.pdf); */ }); } function downloadPDF() { var data = getSampleData(); easypdf.create(data, function(result) { easypdf.download('sample.pdf', result.pdf); // you can download like this as well: // easypdf.download(); // easypdf.download('sample.pdf'); }); } function renderPDF() { var data = getSampleData(); document.getElementById("pdf").innerHTML = "loading..."; easypdf.create(data, function(result) { easypdf.render('pdf', result.pdf); }); } function getSampleData() { var html = '<p>Hello world!</p>'; return { // Base64 encode html html: btoa(html), background: 'https://public.easyinvoice.cloud/img/watermark-draft.jpg', settings: { // "margin-top": 25, // Default to 25 // "margin-right": 25, // Default to 25 // "margin-left": 25, // Default to 25 // "margin-bottom": 25, // Default to 25 // "format": "Letter" // Defaults to A4 } }; } </script> </html> |
As you can see we are adding the url
of the images as watermark inside the pdf
document. And also we have the buttons to render
the pdf document and also download
the pdf document inside the browser as an attachment.