How to create and download a PDF with Angular, Firebase, and PDFMake

Andre Lombaard
2 min readAug 9, 2021

--

I recently had to write functionality to create a serverside PDF to be downloaded by an Angular client application. I hate to admit it, but it took me way longer than initially anticipated. I assume that you are reading this article because you are finding yourself in a similar situation. So here is a quick guide that would hopefully save you some time.

Download a PDF file with Angular, Firebase functions and PDFMake

Installing the PDFMake library

As a first step, install the PDFMake npm package in your Firebase functions project.

npm install pdfmake

If you are not familiar with the PDFMake library, I suggest you read through the documentation to familiarize yourself with the syntax to generate a PDF file. PDFMake also provides a handy tool called the PDFMake Playground that makes it extremely easy to build and test PDF files in real-time. For this article, I will use an elementary example to showcase creating a PDF file serverside.

Writing the Firebase function

Post-installation of the PDFMake library, we need to import the library and font bundles.

const PdfMake = require('pdfmake');
const fonts = require('pdfmake/build/vfs_fonts.js');

We also need to import and set up CORS. Please note that we will just set up CORS for this article so that anyone can call the function by setting origin equal to true. Make sure that you understand how CORS work and set it up in such a way as to protect your function from malicious attacks.

const cors = require('cors')({ origin: true });

In my case, I had to create a relatively big PDF. Luckily Firebase makes it easy to configure the allocated memory assigned to any particular function, should you need to. For example, below is the configuration I used to increase the memory from 256MB to 512MB.

const runtimeOpts = {
timeoutSeconds: 300,
memory: VALID_MEMORY_OPTIONS[2] // Index 2 represents 512MB
}

The firebase function to create an elementary PDF file and send it as a response is outlined below.

Writing the Angular function

--

--

No responses yet