How to Render HTML
If you generate documents yourself, such as invoices, reports, or Open Graph images, you can turn their HTML into a PDF, an image or Markdown. Send the HTML in the html option instead of a url, and choose the output with format, as with any capture. Every format works: PDF, PNG and the other image formats, Markdown, and HTML.
Render an invoice to PDF
Send a complete document that starts with <!doctype html>, and give it a <title>: the PDF takes its title from it.
import { writeFile } from "node:fs/promises";
import { ScreenshotScoutClient } from "@screenshotscout/sdk";
const client = new ScreenshotScoutClient(); // Reads SCREENSHOTSCOUT_ACCESS_KEY
const html =
"<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>";
const response = await client.captureFromHtml(html, { format: "pdf" });
await writeFile("invoice.pdf", response.bytes);from pathlib import Path
from screenshotscout import CaptureFormat, CaptureOptions, ScreenshotScoutClient
client = ScreenshotScoutClient() # Reads SCREENSHOTSCOUT_ACCESS_KEY
html = "<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>"
response = client.capture_from_html(html, CaptureOptions(format=CaptureFormat.PDF))
Path("invoice.pdf").write_bytes(response.bytes)import com.screenshotscout.BinaryCaptureResponse;
import com.screenshotscout.CaptureFormat;
import com.screenshotscout.CaptureOptions;
import com.screenshotscout.ScreenshotScoutClient;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
var client = ScreenshotScoutClient.fromEnv(); // Reads SCREENSHOTSCOUT_ACCESS_KEY
var html = "<!doctype html><html><head><title>Invoice #1042</title></head>"
+ "<body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>";
var options = CaptureOptions.builder().format(CaptureFormat.PDF).build();
var response = (BinaryCaptureResponse) client.captureFromHtml(html, options);
Files.write(Path.of("invoice.pdf"), response.bytes());
}
}using ScreenshotScout;
using var client = new ScreenshotScoutClient(); // Reads SCREENSHOTSCOUT_ACCESS_KEY
var html = "<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>";
var response = (BinaryCaptureResponse)await client.CaptureFromHtmlAsync(
html,
new CaptureOptions { Format = CaptureFormat.Pdf });
await File.WriteAllBytesAsync("invoice.pdf", response.Bytes);<?php
use ScreenshotScout\CaptureFormat;
use ScreenshotScout\CaptureOptions;
use ScreenshotScout\Client;
require __DIR__ . '/vendor/autoload.php';
$client = new Client(); // Reads SCREENSHOTSCOUT_ACCESS_KEY
$html = '<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>';
$response = $client->captureFromHtml(
$html,
(new CaptureOptions())->withFormat(CaptureFormat::PDF),
);
file_put_contents('invoice.pdf', $response->bytes());package main
import (
"context"
"log"
"os"
screenshotscout "github.com/screenshotscout/screenshotscout-go"
)
func main() {
client, err := screenshotscout.NewClient() // Reads SCREENSHOTSCOUT_ACCESS_KEY
if err != nil {
log.Fatal(err)
}
html := `<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>`
format := screenshotscout.CaptureFormatPDF
response, err := client.CaptureFromHTML(context.Background(), html, &screenshotscout.CaptureOptions{Format: &format})
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("invoice.pdf", response.Binary.Bytes, 0o644); err != nil {
log.Fatal(err)
}
}require "screenshotscout"
client = ScreenshotScout::Client.new # Reads SCREENSHOTSCOUT_ACCESS_KEY
html = '<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>'
response = client.capture_from_html(
html,
ScreenshotScout::CaptureOptions.new(format: ScreenshotScout::CaptureFormat::PDF)
)
File.binwrite("invoice.pdf", response.bytes)curl "https://api.screenshotscout.com/v1/capture" \
-H "Authorization: Bearer $SCREENSHOTSCOUT_ACCESS_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<!doctype html><html><head><title>Invoice #1042</title></head><body><h1>Invoice #1042</h1><p>Total due: $480.00</p></body></html>",
"format": "pdf"
}' \
-o "invoice.pdf"PDFs use the print media type by default, so your @media print CSS applies. The PDF options, such as pdf_paper_format and pdf_margin, work as they do with a URL.
Render an Open Graph image to PNG
When someone shares a link on a social network or in a chat app, the preview shows the page's Open Graph image: the picture its og:image tag points to. Sites with many pages and no picture for each one, such as docs, changelogs or job listings, often generate these images: they design one HTML template, fill in each page's details, and render it to a PNG.
Open Graph images are usually 1200 × 630 pixels. Set the viewport to that size, and the capture is exactly the image:
{
"html": "<!doctype html><html><head><meta charset=\"utf-8\"><title>Senior Backend Engineer at Acme Inc.</title><style>body { margin: 0; height: 630px; box-sizing: border-box; padding: 72px 80px; display: flex; flex-direction: column; justify-content: space-between; background: #0f172a; color: #fff; font-family: system-ui, sans-serif; } p { margin: 0; font-size: 34px; } .company { color: #94a3b8; } .details { color: #38bdf8; } h1 { margin: 0; font-size: 76px; }</style></head><body><p class=\"company\">Acme Inc.</p><h1>Senior Backend Engineer</h1><p class=\"details\">Remote · $150k–$180k · Full-time</p></body></html>",
"device_viewport_width": 1200,
"device_viewport_height": 630
}Generate the image once, when the page is published or changes, and save it: screenshot URLs expire, and the og:image tag needs a permanent URL. Save the PNG to your own storage, or set storage_mode to external to have it uploaded to your bucket. Then point the page's tag at it:
<meta property="og:image" content="https://jobs.example.com/og/senior-backend-engineer.png" />Load fonts, images and stylesheets
The page has no URL, so relative URLs such as /logo.png or styles.css don't load. You have three options:
- Use absolute
httpsURLs. - Embed small files as
data:URIs. They count toward the 5 MB limit on the request body, so load large images from URLs. - Add
<base href>to the<head>, so relative URLs resolve against your site:
<!doctype html>
<html>
<head>
<title>Report</title>
<base href="https://example.com/" />
<link rel="stylesheet" href="styles/report.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" />
</head>
<body>
<img src="images/logo.png" alt="Example" />
</body>
</html>Fonts, module scripts and fetch requests from the page carry Origin: null, so the server that hosts them must allow them with Access-Control-Allow-Origin. Public CDNs such as Google Fonts, jsDelivr and unpkg do. Images and classic stylesheets don't need it.
Wait for scripts
Scripts in the HTML run before the capture. By default, we capture once the network is almost idle (networkidle2), which covers most scripts that load data. If a script keeps drawing after that, such as an animated chart, add a delay:
{
"html": "<!doctype html><html><head><title>Revenue</title><script src=\"https://cdn.jsdelivr.net/npm/chart.js\"></script></head><body><canvas id=\"chart\"></canvas><script>/* Draw the chart */</script></body></html>",
"delay": 1
}What the page can't do
The page's origin is null, and it isn't a secure context, so some browser features don't work:
localStorage,sessionStorage,document.cookieandindexedDBthrow an error.crypto.subtle,crypto.randomUUID, service workers, the clipboard and geolocation aren't available.history.pushStatethrows, and afetchwith a relative URL fails unless the page has a<base href>.
Documents that only display content don't need any of these. If a script reads settings from storage, guard the access:
let theme = "light";
try {
theme = localStorage.getItem("theme") ?? theme;
} catch {
// Storage isn't available in this page
}Load images behind a login
To load images or other files that need a session, pass the session cookie in cookies with a Domain attribute:
{
"html": "<!doctype html><html><head><title>Monthly report</title></head><body><img src=\"https://app.example.com/charts/revenue.png\" alt=\"Revenue\" /></body></html>",
"format": "pdf",
"cookies": ["session=abc123; Domain=app.example.com; Path=/; Secure; HttpOnly"]
}With html, cookies follow these rules:
- Each cookie needs a
Domainattribute, because the page has no URL to scope it to. - Cookies are sent as
SameSite=None; Secure, over HTTPS only. - Cookies with the
__Host-prefix, and cookies withSameSite=LaxorSameSite=Strict, are rejected.
Signed requests
HTML is sent in a POST request, which can't be signed. If your API key has Require signed requests enabled, use another API key without it for HTML. In the SDKs, use a client without a secret key.