Creating PDFs in C# with Azure Functions

Thomas Pentenrieder
medialesson
Published in
2 min readOct 25, 2022
Photo by Volodymyr Hryshchenko on Unsplash, Pdf Icons by Pixel Buddha — Flaticon

For a customer project we needed to create PDF pricelists from JSON in C# using Azure Functions. And while there are several paid & free options in the .NET ecosystem for PDF gereation, I never found a way that I really liked. Here’s an option that worked great for me, although it still feels a bit hacky.

One easy to use albeit limited option is Puppeteer, a tool to run headless Chrome mostly used for things like UI tests. But it also offers Export-to-PDF functionality which is awesome. This allows you to create PDF files directly from HTML which is my preferred way of layouting documents. Combined with Handlebars templates we can quickly dynamically generate documents this way.

Since this is a NodeJS tool it obviously would work with Azure Functions written in JS / Typescript, but here we needed to use C#. For this, we’re using the excellent Puppeteer Sharp wrapper. And since we’re in Azure, we’d like to store our generated files inside Azure BLOB Storage.

Note: Due to some limitations with the Azure Functions runtime and how Chrome is launched this approach currently only works on a Linux host!

Here’s what the code below does step by step:

  1. Get price list as JSON from Azure BLOB trigger & deserialize it
  2. Setup Puppeteer Sharp to be used to render HTML & Export as PDF
  3. Create HTML Template with Handlebars.Net
  4. Upload PDF result to Azure BLOB Storage
  5. (Optional) Save PDF to disc when debugging locally

--

--