How to make a pdf from user input on website

Problem: Generate a pdf on a website (client side) with user input.

Solution: Use the pdfMake library! To get started, make a html file:

<!DOCTYPE html>
    <meta charset="UTF-8">
    <title>pdfmake - Basic Example with User Input</title>
    <script src="pdfmake.js">// </script>
    <script src="vfs_fonts.js">// </script>
      function makePdf() {
        let dd = {
          content: [
            'Hello {name}!'
        let n = document.getElementById("inputName").value;
        dd = JSON.stringify(dd);
        dd = dd.replace(/{name}/g, n);
        dd = JSON.parse(dd);
      html {
        display: table;
        margin: auto;
    <h1>Basic Example - pdfmake</h1>
    <h2>Insert a name</h2>
    <input type="text" id="inputName" value=""><br><br>    
    <button onclick="makePdf()">Make PDF</button>

Save the above code as an html file. Also save the two scripts (pdfmake.js and vfs_fonts.js) in the same folder.

Then open the html file in a browser, fill in a name, and click the button. You should now be able to save or open a pdf file:

The pdf file:

The json object dd contains the blueprint for the pdf. The playgroud is very useful for building more complicated pdfs.

Since dd is a json object it needs to be stringified to replace {name} with the user input. If you need to make several replacements I recommend this function:

function jsonReplaceAll(obj, searchvalue, newvalue) {
  var re = new RegExp(searchvalue,"g")
  obj = JSON.stringify(obj).replace(re, newvalue)
  return JSON.parse(obj);

Categories: Uncategorized

Tags: , , , , ,