Tech .NET and C#

A social card for every page

How my site draws its own link preview images at build time with SkiaSharp: the layout, Bangla text, caching, and the bugs on the way.

বাংলায় পড়ুন

When you paste a link into WhatsApp, Facebook or LinkedIn, you get a little preview: a picture, a title and a line of text. That picture is called a social card, or an og:image. For a long time, every page on my site shared the same one. A post about databases and a photo story from Sylhet looked exactly the same in a chat.

So I made the site draw its own cards. Every post, project and page now gets a card made for it, when the site is built. Here is the card for my last post:

The social card for my PageSpeed post: the title in large serif type on dotted notebook paper, a CSS logo sticker on the right, and the date at the bottom.

This post is how that works.

In short

  • No browser, no service. The cards are drawn in C# with SkiaSharp during the Statiq build. 29 cards on the site today.
  • Bangla needed real text shaping. Drawing Bangla letter by letter breaks the joined letters. HarfBuzz fixes it.
  • The title picks its own size. The code tries big sizes first and stops at the first one that fits in three lines.
  • Cards are cached by a hash of everything drawn on them, so a build only draws the cards that changed.

Why not take a screenshot?

The common way to make these cards is to build a small HTML page for the card and take a screenshot of it with a headless browser. Vercel also has a service that does this.

I didn't want either. A headless browser is a big thing to install just to draw a picture, and it would make every build slower. A service means my build depends on someone else's server. My site is already a C# program (Statiq is a .NET static site generator), so I wanted the cards to be drawn by that same program.

SkiaSharp is the .NET wrapper around Skia, the graphics library that Chrome and Android use to draw things. It can open a blank image, draw text, shapes and pictures on it, and save it as a PNG. That's all a card needs.

What is on a card

A card is 1200 by 630 pixels. That is the size Facebook, LinkedIn and X all expect. Every card has the same parts, so they look like they belong to one site:

  1. The paper

    Notebook paper, like the site: a dot grid and a double red margin line on the left.

  2. A small label

    Handwritten, in the section's colour. "tech · Tools and AI", for example.

  3. The title

    As big as it can be. More on that below.

  4. The description

    One or two lines, but only if the title left room.

  5. A sticker or a photo

    An icon on a tilted sticker with a piece of tape. Photo stories and the about page get a polaroid instead.

  6. The footer

    My logo, the domain, and a date or a post count.

The colours come from data/theme.yml, the same file the site's CSS is made from. A card can't read CSS, so the renderer reads the theme file and pulls out the ink, paper and accent colours. If I change the theme, the cards change with it.

Making the title fit

Titles are different lengths. "Records, init and with" is short. Some titles are long enough to fill the card. A fixed font size would make the short ones look lost and the long ones spill off the edge.

So the renderer tries a list of sizes, biggest first, and stops at the first one that fits in three lines:

float[] sizes = bn ? new float[] { 60, 54, 48, 42, 38 }
                   : new float[] { 74, 66, 58, 52, 46, 42 };

foreach (float size in sizes)
{
    using var f = new SKFont(bn ? _bnBold : _title, size);
    var lines = Wrap(title, s => Measure(s, f, bn), maxWidth).ToList();
    if (lines.Count <= 3)
        return (lines, size, size * (bn ? 1.42f : 1.1f));
}

Wrap is a plain word wrap. It adds words to a line until the next word would make the line too wide, then starts a new line. If even the smallest size needs more than three lines, the third line ends with "…".

The description has a similar rule. It only shows when the title took two lines or fewer, and it is cut at two lines. When it is cut, the last word is dropped if the "…" wouldn't fit after it. A description that stops halfway through a word looks broken.

Bangla gets its own sizes and more space between lines. Bangla letters have marks above and below the line, and with English line spacing they touch the line above.

Bangla text was broken at first

Half my site is in Bangla, so the cards had to work in Bangla too. This was the hardest part.

BUGhighfixed

Bangla titles look wrong on the cards

symptom

Bangla titles were readable, but wrong. Joined letters like ক্ষ and ন্ত showed up as two separate letters with a hasanta (্) between them. Vowel signs like ি sat in the wrong place.

cause

DrawText in SkiaSharp draws one glyph per character, left to right. English works fine that way. Bangla doesn't. The font has special glyphs for joined letters and rules for where vowel signs go, and something has to read those rules and pick the right glyphs. That step is called text shaping, and plain DrawText doesn't do it.

fix

Run Bangla text through HarfBuzz first, using the SkiaSharp.HarfBuzz package. HarfBuzz is the shaping engine that browsers use. It takes the text and the font and returns the right glyphs with their exact positions. Then I draw those glyphs.

lesson

If text in your language looks right in a browser and wrong in your own drawing code, the missing piece is probably shaping.

The drawing part looks like this. HarfBuzz returns a list of glyphs and a position for each one, and Skia draws them as one block of text:

SKShaper.Result shaped = Shape(shaper, text, font);

using var builder = new SKTextBlobBuilder();
var run = builder.AllocatePositionedRun(font, shaped.Codepoints.Length);
for (int i = 0; i < shaped.Codepoints.Length; i++)
{
    run.Glyphs[i] = (ushort)shaped.Codepoints[i];
    run.Positions[i] = shaped.Points[i];
}

using SKTextBlob? blob = builder.Build();
if (blob != null) c.DrawText(blob, x, y, paint);

The measuring has to be shaped too. If I measured Bangla the simple way and drew it the shaped way, the word wrap would get the widths wrong and lines would run off the card.

Two smaller things came with it:

  • Handwriting. English labels use Caveat, a handwriting font. Caveat has no Bangla letters, so Bangla labels use Hind Siliguri in bold.
  • Mixed text. A card counts as Bangla if its language is Bangla, or if its title has any Bangla letter in it. That way an English page with a Bangla title still gets the right font.

Here is the card for the Bangla tech page:

The social card for the Bangla tech section: the title টেক in bold Bangla type, a Bangla description below it, and a terminal icon on the sticker.

Drawing only what changed

Drawing a card takes a moment, and with all my drafts and sample posts turned on, the site has more than a hundred of them. I didn't want to draw all of them on every build when I only fixed a typo in one post.

So every card is saved in a folder called .og-cache, and the file name is a hash of everything drawn on that card:

public string Hash()
{
    string photo = Photo is not null && File.Exists(Photo)
        ? $"{Photo}|{File.GetLastWriteTimeUtc(Photo).Ticks}" : "";
    string key = string.Join("\u001f",
        OgRenderer.Version, SiteData.Profile.Brand, Seo.Host,
        SiteData.Theme.SocialSignature(),
        Title, Description, Lang, Variant, Label, Accent, Icon, Meta,
        photo, Caption ?? "");
    return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key)))[..16]
        .ToLowerInvariant();
}

If the file for that hash is already there, the build copies it. If not, it draws a new one. Change a title and only that card is drawn again. Change the theme colours and every card is drawn again, because the theme is part of the hash. The GitHub Actions deploy keeps this folder between runs, so the server gets the same benefit.

There is one thing the hash can't see: the drawing code itself. If I move the sticker 10 pixels to the left, no title or colour changed, so every hash stays the same and the build happily serves the old cards. That is what OgRenderer.Version is for. It is a number at the top of the renderer, and it is part of every hash. When I change how cards are drawn, I bump it. It is at 8 now, which tells you how many times I've changed my mind about the layout.

I forgot to bump it more than once, and each time I spent a few minutes confused about why my change wasn't showing up.

The apostrophe bug

The cards were the big part, but I also cleaned up the tags in the page head that point to them. That turned up a bug that had been there for a while.

BUGmediumfixed

Broken apostrophes in share previews

symptom

Some link previews showed the description with &#x27; where an apostrophe should be. "doesn't" came out as "doesn't".

cause

The text was escaped twice. Razor turns ' into &#x27; when it writes an attribute. A later step in the build escaped the head again, so the & became &amp;. Browsers undo one layer, so the page looked fine. Link preview bots showed what was left.

fix

A small Seo.Attr() helper that escapes only the four characters that matter inside a double-quoted attribute (&, ", < and >), and hands Razor text that it won't escape again.

lesson

Check your link previews with a real preview tool, not just the page. The bug was invisible in the browser.

While I was there, I added the tags that were missing: the image size, its type, alt text for the image, and the twitter: tags so X shows a large card too.

What I'd still change

The cache never deletes anything. Every time a title or a description changes, a new card is saved and the old one stays. The site has 29 cards right now, but my local .og-cache folder has about 1,600 files in it, around 100 MB. It doesn't break anything, since the build only copies the cards it needs. But a small cleanup step that removes cards no page asked for would be easy to add, and I should add it.

What I learned

  • You don't need a browser to draw an image. For a fixed layout like this, a graphics library is smaller, faster and easier to run in CI.
  • Text is the hard part, not shapes. Fitting the title, cutting the description and shaping Bangla took far more code than the paper, the sticker and the tape.
  • Put everything you draw in the cache key, and add a version number for the code itself, because the code is the one input a hash can't see.
  • Test the preview, not the page. Link preview bots read your HTML differently from a browser.

Now when I share a post, the preview tells you what the post is about before you open it. That was the whole point.