Search code examples
firebasepdf-generationpdfmake

How to generate a pdf as a result of HTTP request firebase function?


How to generate a pdf as a result of HTTP request firebase function with pdfmake?

Let's say I have the following JSON

{
  "user" : "John Doe",
  "booksOwned":[
      {
        "title":"Fancy Coffins to Make Yourself",
        "author":"Dale L. Power"
      },
      {
        "title":"Knitting With Dog Hair",
        "author":"K Crolius"
      },
      {
        "title":"Everything I Want to Do is Illegal",
        "author":"Joel-Salatin"
      }
    ]
}

And I want a PDF that greets the User and lists all books in a table. This should be the result when I call a firebase function with this JSON. How can I do this with pdfmake?


Solution

  • first install pdfmake

    npm install pdfmake
    

    and use this following function, notice that you have to ajust the docDefinition for your needs

    exports.getPDF = functions.https.onRequest(async (req, res) => {
        //...
        var data = JSON.parse(req.query.json); //asume json is given as parameter
        //fonts need to lay in the functions directory
        var fonts = {
            Roboto: {
                normal: './fonts/Roboto-Regular.ttf',
                bold: './fonts/Roboto-Medium.ttf',
                italics: './fonts/Roboto-Italic.ttf',
                bolditalics: './fonts/Roboto-MediumItalic.ttf'
            },
        };
    
        var PdfPrinter = require('pdfmake'); //needs to installed via "npm install pdfmake"
        var printer = new PdfPrinter(fonts);
    
        var docDefinition ={
    content: [
            
            {text: 'Hello User:', style: 'header'},
            {
                table: {
                    body: [
                        ['book', 'author',],
                        ['book1','author1'],
                        ['book2','author2'],
                        ['book3','author3']
                    ]
                }
            }
        ]
    }
    
    
        var options = {
            // ...
        }
    
        var pdfDoc = printer.createPdfKitDocument(docDefinition, options);
        pdfDoc.pipe(res.status(200));
        pdfDoc.end();
    
    });