Skip to content
shotsmith
Features Docs Guides Pricing Changelog Sign inStart free

Generate Open Graph images from HTML

Design social preview images in HTML and CSS, and render them to PNG with one API call: the approach this site uses for its own.

7 min read

When someone shares a link on LinkedIn, Slack, X or iMessage, the preview image decides whether it gets clicked. Making one by hand for every blog post, product or profile doesn’t scale, and image libraries make you position text pixel by pixel. The easier way is to design the card in HTML and CSS, which you already know, and render it to a PNG.

The share images for the guides on this site are made exactly this way, with shotsmith.

1. Design the card in HTML

Open Graph images are 1200 × 630 pixels. Build a page at exactly that size, with your fonts, colours and logo. Use flexbox to centre text, and CSS line-clamp so long titles don’t overflow:

<html><body style="margin:0">
  <div style="width:1200px;height:630px;display:flex;flex-direction:column;justify-content:center;
              padding:80px;box-sizing:border-box;background:#0F1B2D;color:#fff;font-family:Inter,sans-serif">
    <p style="font-size:28px;color:#F49AC6;margin:0">Guides</p>
    <h1 style="font-size:64px;line-height:1.1;margin:24px 0 0;display:-webkit-box;
               -webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden">
      How to take website screenshots in Python
    </h1>
  </div>
</body></html>

2. Render it to PNG

Send the HTML in a POST request, with a 1200 × 630 viewport, and save the PNG:

import { Shotsmith } from '@shotsmith/sdk';

const shotsmith = new Shotsmith({ accessKey: 'YOUR_ACCESS_KEY' });

import { writeFile } from 'node:fs/promises';

const file = await shotsmith.take({
  html: '<html><body style=\'margin:0\'>…</body></html>',
  viewport_width: 1200,
  viewport_height: 630,
  format: 'png',
});

await writeFile('og.png', file);
<?php

require 'vendor/autoload.php';

use Shotsmith\Client;

$shotsmith = new Client('YOUR_ACCESS_KEY');

$file = $shotsmith->take([
    'html' => '<html><body style=\'margin:0\'>…</body></html>',
    'viewport_width' => 1200,
    'viewport_height' => 630,
    'format' => 'png',
]);

file_put_contents('og.png', $file);
curl -X POST "https://shotsmith.dev/v1/take" \
  -H "X-Access-Key: YOUR_ACCESS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<html><body style='\''margin:0'\''>…</body></html>",
    "viewport_width": 1200,
    "viewport_height": 630,
    "format": "png"
  }' \
  --fail-with-body \
  -o og.png
import { writeFile } from 'node:fs/promises';

const res = await fetch('https://shotsmith.dev/v1/take', {
  method: 'POST',
  headers: {
    'X-Access-Key': 'YOUR_ACCESS_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    html: '<html><body style=\'margin:0\'>…</body></html>',
    viewport_width: 1200,
    viewport_height: 630,
    format: 'png',
  }),
});
if (!res.ok) throw new Error((await res.json()).error_message);

await writeFile('og.png', Buffer.from(await res.arrayBuffer()));
import json
import urllib.request

body = {
    "html": "<html><body style='margin:0'>…</body></html>",
    "viewport_width": 1200,
    "viewport_height": 630,
    "format": "png"
}

req = urllib.request.Request(
    "https://shotsmith.dev/v1/take",
    data=json.dumps(body).encode(),
    headers={"X-Access-Key": "YOUR_ACCESS_KEY", "Content-Type": "application/json"},
    method="POST",
)

# Raises urllib.error.HTTPError on a 4xx/5xx response
with urllib.request.urlopen(req, timeout=120) as res, open("og.png", "wb") as f:
    f.write(res.read())
<?php

$ch = curl_init('https://shotsmith.dev/v1/take');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['X-Access-Key: YOUR_ACCESS_KEY', 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode([
        'html' => '<html><body style=\'margin:0\'>…</body></html>',
        'viewport_width' => 1200,
        'viewport_height' => 630,
        'format' => 'png',
    ]),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120,
]);
$body = curl_exec($ch);

if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
    throw new RuntimeException(json_decode($body, true)['error_message']);
}

file_put_contents('og.png', $body);
package main

import (
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	body := strings.NewReader(`{
	  "html": "<html><body style='margin:0'>…</body></html>",
	  "viewport_width": 1200,
	  "viewport_height": 630,
	  "format": "png"
	}`)

	req, _ := http.NewRequest("POST", "https://shotsmith.dev/v1/take", body)
	req.Header.Set("X-Access-Key", "YOUR_ACCESS_KEY")
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		msg, _ := io.ReadAll(res.Body)
		panic(string(msg))
	}

	out, err := os.Create("og.png")
	if err != nil {
		panic(err)
	}
	defer out.Close()
	io.Copy(out, res.Body)
}
require "net/http"
require "json"

body = {
  "html" => "<html><body style='margin:0'>…</body></html>",
  "viewport_width" => 1200,
  "viewport_height" => 630,
  "format" => "png"
}

res = Net::HTTP.post(
  URI("https://shotsmith.dev/v1/take"),
  body.to_json,
  "X-Access-Key" => "YOUR_ACCESS_KEY",
  "Content-Type" => "application/json"
)
raise res.body unless res.is_a?(Net::HTTPSuccess)

File.binwrite("og.png", res.body)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class Request {
    public static void main(String[] args) throws Exception {
        var body = """
            {
              "html": "<html><body style='margin:0'>…</body></html>",
              "viewport_width": 1200,
              "viewport_height": 630,
              "format": "png"
            }
            """;

        var request = HttpRequest.newBuilder(URI.create("https://shotsmith.dev/v1/take"))
            .header("X-Access-Key", "YOUR_ACCESS_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();

        var res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofFile(Path.of("og.png")));
        if (res.statusCode() != 200) {
            throw new RuntimeException("HTTP " + res.statusCode());
        }
    }
}
using System;
using System.IO;
using System.Net.Http;
using System.Text;

using var http = new HttpClient();
http.DefaultRequestHeaders.Add("X-Access-Key", "YOUR_ACCESS_KEY");

var body = """
    {
      "html": "<html><body style='margin:0'>…</body></html>",
      "viewport_width": 1200,
      "viewport_height": 630,
      "format": "png"
    }
    """;

var res = await http.PostAsync(
    "https://shotsmith.dev/v1/take",
    new StringContent(body, Encoding.UTF8, "application/json")
);
res.EnsureSuccessStatusCode();

await File.WriteAllBytesAsync("og.png", await res.Content.ReadAsByteArrayAsync());

Fonts load like on any web page: link Google Fonts or your own hosted fonts with absolute URLs, and the render waits for them.

3. Reference it from your page

<meta property="og:image" content="https://your-site.com/og/my-post.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">

Generate once, not on every request

Share images rarely change, so make them when the content is published or edited, and store the PNG (in your public folder, S3 or a CDN), rather than rendering on every visit. Each render uses one of your renders; serving a stored file costs nothing.

  • At build time: a script that loops over your posts and saves each card, like the one this site uses.
  • On save: a background job in your CMS that renders the card when a post is published.
  • Straight to your bucket: add store=true and a storage_path such as og/{id}, and the PNG is uploaded to your own S3, R2 or Spaces bucket.

Or use a screenshot of the page itself

For directories, link aggregators or portfolios, the best preview is often the page itself. A signed screenshot URL with viewport_width=1200, viewport_height=630 and cache=true works directly as an og:image.