Automatically generating PDF’s from a template is no small feat without the proper tools, but Google Apps Script makes it simple. In less than 50 lines of JavaScript we can create an API that generates PDF’s based on a template in our Google Drive.
Use cases are endless, but my current company uses it for generating invoices on demand from my Chrome Extension.
To get started, sign in to Google Drive and create a new Google Apps Script. If you haven’t done this before, you’ll have to connect it by searching under New > More > Connect more apps.
Once you’re inside the editor, we can start building the API. Our API will only have one method: GET. Since Apps Script maps requests to function names, we’ll call our first function as mandated in the docs: doGet
.
We can extract the URL parameters from e.parameters
. After generating the PDF, we’ll return a download link and other information inside a JSON object. Now let’s add the functions that do the real work.
The template file will have <variables>
surrounded by carats that the above script will replace. For example, if our template contains the text <price>
, it will be swapped out with the price URL parameter.