How to Convert HTML to an Image in .NET With Managed Code
Convert HTML to PNG or JPEG in .NET with Playwright, managed renderers, or Chromium wrappers. Compare setup, fidelity, deployment, errors, and cost.

To convert HTML to an image in .NET, choose the renderer that matches your HTML. For modern pages with JavaScript, web fonts, external images, and responsive CSS, use Playwright for .NET and save a browser screenshot. For controlled, simple markup, HtmlRenderer.Core can render HTML with managed C# and without an external browser. Chromium wrappers such as CoreHtmlToImage provide a smaller conversion API but still require a browser binary.
This guide shows each approach, including URL and HTML-string input, PNG and JPEG output, full-page and element screenshots, deployment, troubleshooting, and an API alternative when you do not want to operate a browser.
1. Choose the right rendering approach
| Approach | Best for | Browser required | Rendering scope |
|---|---|---|---|
| Playwright .NET | Modern websites, JavaScript, responsive layouts, authenticated pages | Yes; Playwright-managed browser binaries | Chromium browser behavior, including full-page and element screenshots |
| HtmlRenderer.Core | Simple, controlled HTML where a browser is unnecessary | No external browser | The package states HTML 4.01 and CSS level 2 support |
| CoreHtmlToImage | A convenience API around Chromium | Yes; PuppeteerSharp downloads a compatible Chromium binary on first use | Headless Chromium rendering |
| Mescius Document Solutions for Imaging | Teams evaluating a commercial, vendor-supported component | Confirm the vendor’s current deployment model | Commercial HTML browser APIs, including GcHtmlBrowser |
Validate your actual HTML, CSS, fonts, images, JavaScript, operating system, container image, and target framework. The available research does not establish comparative benchmarks or compatibility tests.

2. Convert a URL with Playwright .NET
Playwright’s official .NET setup installs the Microsoft.Playwright package, then installs the browser binaries required by the selected Playwright release. Its screenshot API can write to a path or return image bytes, and it supports full-page and locator-level capture.
Install the package and browser
dotnet new console -n HtmlToImage
cd HtmlToImage
dotnet add package Microsoft.Playwright
dotnet build
# Run the generated Playwright browser installation script.
# The exact generated path can vary by SDK and shell; inspect the build output
# or Playwright's current .NET installation guide for the command.
Playwright browser binaries are version-specific. When you update the NuGet package, rerun browser installation in development, CI, and the production image as part of the deployment process. See the Playwright .NET getting-started guide, screenshot guide, and browser management documentation.
Complete console program
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync(new BrowserNewPageOptions
{
ViewportSize = new ViewportSize { Width = 1440, Height = 900 },
DeviceScaleFactor = 1
});
await page.GotoAsync("https://example.com", new PageGotoOptions
{
WaitUntil = WaitUntilState.NetworkIdle,
Timeout = 60_000
});
await page.ScreenshotAsync(new PageScreenshotOptions
{
Path = "page.png",
FullPage = true,
Type = ScreenshotType.Png
});
Use WaitUntilState.Load when a site keeps long-lived analytics connections open. Use a selector wait or a short delay when content is rendered after navigation:
await page.GotoAsync(url, new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded });
await page.Locator("main").WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible });
await page.WaitForTimeoutAsync(500);
await page.ScreenshotAsync(new PageScreenshotOptions { Path = "ready.png", FullPage = true });
3. Convert an HTML string instead of a URL
Load your markup with Playwright’s page-content API, then capture the document. This keeps the conversion in memory and is useful for invoices, reports, emails, and generated templates.
using Microsoft.Playwright;
const string html = """
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.card { border: 1px solid #ddd; padding: 24px; width: 520px; }
</style>
</head>
<body>
<section class="card"><h1>Invoice</h1><p>Generated from HTML.</p></section>
</body>
</html>
""";
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync(new BrowserNewPageOptions
{
ViewportSize = new ViewportSize { Width = 900, Height = 700 }
});
await page.SetContentAsync(html, new PageSetContentOptions
{
WaitUntil = WaitUntilState.NetworkIdle,
Timeout = 60_000
});
var bytes = await page.ScreenshotAsync(new PageScreenshotOptions
{
Type = ScreenshotType.Jpeg,
Quality = 90,
FullPage = true
});
await File.WriteAllBytesAsync("document.jpg", bytes);
For local fonts or images, use file URLs only when the browser context is configured to permit them, or serve the assets from a controlled local HTTP endpoint. External resources can make output nondeterministic or fail in an isolated container.
4. Screenshot one element or control the output
var chart = page.Locator("#chart");
await chart.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible });
await chart.ScreenshotAsync(new LocatorScreenshotOptions
{
Path = "chart.png",
Type = ScreenshotType.Png
});
- Full page: set
FullPage = truefor the complete scrollable document. - Viewport: set
ViewportSizewhen responsive breakpoints matter. - Retina output: increase
DeviceScaleFactorfor higher pixel density, while accounting for larger files. - JPEG: select
ScreenshotType.Jpegand setQuality; use PNG for sharp text, transparency, or lossless output. - Stable layout: wait for a meaningful selector, fonts, images, and application data before capture.
5. Managed rendering with HtmlRenderer.Core
HtmlRenderer.Core advertises 100% managed C# rendering with no external dependency and image generation. Its package description states support for HTML 4.01 and CSS level 2, and lists .NET Standard 2.0 and .NET 8.0 or higher targets. That scope is substantially narrower than a current browser: do not expect JavaScript or modern CSS parity without validating your own templates.
dotnet add package HtmlRenderer.Core
The package’s rendering adapters and image APIs vary by package version and target framework. Start from the versioned NuGet documentation and keep the renderer behind an interface so you can replace it if your templates require browser features. A typical integration has this shape:
// Verify the exact adapter and RenderToImage overload for the package version
// selected by your project before compiling this example.
using System.Drawing;
using TheArtOfDev.HtmlRenderer.Core;
string html = "<html><body><h1>Report</h1></body></html>";
using Bitmap bitmap = HtmlRender.RenderToImage(html, 800, 1200);
bitmap.Save("report.png", System.Drawing.Imaging.ImageFormat.Png);
On platforms where System.Drawing is unsupported or restricted, use the package’s supported image adapter or choose a browser-based route. Confirm current maintenance, target frameworks, and platform guidance before committing to this dependency.
6. Chromium through CoreHtmlToImage
CoreHtmlToImage 2.0.0 is described as converting HTML strings or URLs to image bytes through headless Chromium via PuppeteerSharp. Its listing says the first use downloads a compatible Chromium binary and caches it for later runs. This reduces application code, but it does not remove browser installation, cache permissions, startup time, or target-framework concerns; the listing reports a .NET 10.0 target.
dotnet add package CoreHtmlToImage
Use the package’s current README for the exact constructor and conversion method for your selected version. Treat the browser download as a deployment step in CI and production rather than relying on a writable runtime home directory.
7. Commercial component option
Mescius Document Solutions for Imaging documents GcHtmlBrowser and a migration from the obsolete GcHtmlRenderer. Its documentation also describes applying a GcImaging license key. This is an option for teams evaluating vendor-supported components. Confirm current editions, licensing, supported runtimes, and deployment terms directly with Mescius.
8. A practical decision checklist
- Choose Playwright when the page depends on JavaScript, modern CSS, web fonts, responsive breakpoints, or browser authentication.
- Choose HtmlRenderer.Core only when its stated HTML and CSS scope covers your templates and avoiding a browser is more important than browser fidelity.
- Choose a Chromium wrapper when you want a simpler API but can operate the browser binary it downloads.
- Choose a commercial component after reviewing its current license and support terms.
- Run representative fixtures containing long pages, missing images, web fonts, RTL text, SVG, forms, animations, and authenticated content before production.
9. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Executable not found | Playwright or PuppeteerSharp browser binaries were not installed in the runtime image. | Run the version-matched browser installation step during image build and ensure the process can read the browser cache. |
| Blank or partially rendered image | Capture occurred before JavaScript, fonts, images, or data finished loading. | Wait for a meaningful selector, image completion, network idle where appropriate, or a bounded delay. |
| Navigation timeout | The page is slow, blocked, or maintains open connections. | Set an explicit timeout, use DOMContentLoaded instead of network idle, and inspect the target from the same network environment. |
| Different layout in CI | Viewport, device scale, fonts, timezone, locale, or browser version differs. | Pin these settings and install the browser version expected by the Playwright package. |
| Missing external images | Requests are blocked, URLs are inaccessible, or the capture runs before images load. | Use reachable HTTPS assets, wait for image completion, and log failed requests during diagnosis. |
| CSS or JavaScript does not work in HtmlRenderer.Core | The template exceeds the package’s stated HTML 4.01/CSS 2 scope. | Reduce the markup or switch to a browser renderer. |
| First request is slow with CoreHtmlToImage | Chromium is being downloaded and initialized. | Warm the dependency during deployment and retain its cache between invocations where possible. |
| Output is too large | Full-page dimensions or device scale factor produce many pixels. | Capture an element, reduce viewport or scale, use JPEG quality controls, or resize after capture. |
10. Performance, reliability, and cost
Browser rendering has startup and memory costs. Reuse a browser process and create pages per job instead of launching a new browser for every image, while isolating untrusted content according to your security policy. Set bounded navigation and selector timeouts, record the URL and renderer version, and retry only failures that are safe to repeat. Avoid indefinite waits for sites that keep analytics or websocket connections open.
Managed rendering avoids browser installation but trades away modern web compatibility. A browser wrapper has the same operational concerns as Playwright, including binary downloads and cache permissions. The research provides no independent speed, memory, or image-fidelity benchmarks, so measure your own representative templates.
11. Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF output. Its capture pipeline accepts consent banners before the shot and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

Use the API when you need a URL capture without installing Playwright or maintaining Chromium. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also supports full-page and selector capture, dark mode, device presets, custom viewports, retina scale, PDF settings, custom CSS and JavaScript, clicks, waits, blocked requests, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
Free accounts include 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.
12. FAQ
Can .NET convert HTML to PNG without a browser?
Yes, HtmlRenderer.Core advertises managed rendering without an external browser, but its stated HTML 4.01 and CSS 2 scope is narrower than Chromium.
Can Playwright capture an HTML string?
Yes. Set the page content, wait for required resources, and call ScreenshotAsync to a path or byte array.
Why does my screenshot differ between machines?
Fonts, viewport, device scale, locale, timezone, browser version, and network resources can all change layout. Pin those inputs and install the browser version expected by your package.
Should I use PNG or JPEG?
Use PNG for text, transparency, and lossless output. Use JPEG when smaller files matter and a small amount of compression is acceptable.
Does a Chromium wrapper eliminate browser deployment?
No. CoreHtmlToImage uses PuppeteerSharp and reports downloading a compatible Chromium binary on first use, so the binary and cache still need operational planning.


