Post

Base64 image helper for Handlebars

The PDF generator only currently accepts a HTML payload with no external references, this means that all CSS and images and images need to be embedded in the HTML directly.

We don’t want to check those base64 images directly in the templates as that could become difficult to manage. To solve this we created a handler which will convert an image into a base64 encoded string when the templates are compiled.

Template

1
<img src="{{base64ImageSrc './logo.png'}}" alt="image" />

Helper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const base64ImageSrc = (imagePath: string) => {
  const bitmap = fs.readFileSync(path.join(__dirname, 'images', imagePath));
  const base64String = new Buffer(bitmap).toString('base64');

  return new Handlebars.SafeString(`data:image/png;base64,${base64String}`);
}

const hbs = exphbs({
  layoutsDir: path.join(__dirname, '/layouts'),
  extname: '.hbs',
  helpers: { 
    base64ImageSrc: base64ImageSrc
  }
});

In this version we’re using express & handlebars-express to wire this up, this will be later converted into .NET 5 however this is a simple POC to test out some of the templating & PDF conversion.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.