Convert HTML to Image in C# with NReco.ImageGenerator
Render HTML, URLs, and local files to PNG or JPEG in C# with NReco.ImageGenerator, with configuration, deployment limits, troubleshooting, and a hosted alternative.

To convert HTML to an image in C#, install the NReco.ImageGenerator NuGet package, create an HtmlToImageConverter, and call GenerateImage. The library launches wkhtmltoimage underneath, so the output depends on that renderer’s support for HTML, CSS, JavaScript, fonts, and external resources.
using NReco.ImageGenerator;
var html = "<html><body><h1>Hello world</h1></body></html>";
var converter = new HtmlToImageConverter();
byte[] pngBytes = converter.GenerateImage(html, ImageFormat.Png);
File.WriteAllBytes("output.png", pngBytes);
This guide covers HTML strings, URLs, local files, output formats, sizing, timeouts, resource failures, deployment, licensing, and the renderer’s compatibility limits. It also shows a hosted option when maintaining a browser executable is not the right fit.
1. Install NReco.ImageGenerator
Add the package to a .NET project with the .NET CLI:
dotnet add package NReco.ImageGenerator
You can also install it from Visual Studio’s NuGet Package Manager. The standard package is designed around a separately launched wkhtmltoimage process. Your application therefore needs permission to start child processes and access the renderer executable.
2. Convert an HTML string to PNG or JPEG
The shortest implementation is useful for invoices, email previews, badges, chart snapshots, and server-generated thumbnails.

using NReco.ImageGenerator;
string html = @"
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<style>
body { font-family: Arial, sans-serif; padding: 32px; }
.card { width: 640px; border: 1px solid #ddd; padding: 24px; }
</style>
</head>
<body>
<div class='card'>
<h1>Weekly report</h1>
<p>Rendered from an HTML string.</p>
</div>
</body>
</html>";
var converter = new HtmlToImageConverter
{
Width = 720,
Height = 480
};
byte[] jpeg = converter.GenerateImage(html, ImageFormat.Jpeg);
File.WriteAllBytes("report.jpg", jpeg);
ImageFormat.Png is useful for transparency, diagrams, and sharp text. ImageFormat.Jpeg usually produces smaller photographic images and does not preserve transparency. The API reference documents BMP, JPEG, and PNG output.
3. Render a URL or local HTML file
Use GenerateImageFromFile when the input is a URL or a file path. The page’s external CSS, images, and JavaScript must be reachable by the renderer.
using NReco.ImageGenerator;
var converter = new HtmlToImageConverter
{
Width = 1280,
Height = 900,
ExecutionTimeout = 60000
};
converter.GenerateImageFromFile(
"https://example.com/article",
"article.png",
ImageFormat.Png
);
For a local file, pass an absolute path or a file URL that the process can read:
string path = Path.GetFullPath("templates/preview.html");
string fileUrl = new Uri(path).AbsoluteUri;
var converter = new HtmlToImageConverter();
converter.GenerateImageFromFile(fileUrl, "preview.jpg", ImageFormat.Jpeg);
Relative resource references are a frequent source of missing images and styles. Prefer absolute HTTPS URLs for hosted assets, or ensure local assets resolve from the document’s directory and are readable by the application identity.
4. Configure dimensions, scaling, and the renderer process
HtmlToImageConverter exposes the main operational controls:
| Property | Use | Practical guidance |
|---|---|---|
Width |
Sets the viewport or minimum output width. | Set it explicitly for repeatable thumbnails and social cards. |
Height |
Sets the viewport or minimum output height. | Use a generous value for pages whose content extends below the fold. |
Zoom |
Scales rendered content. | Adjust when text appears too small or a fixed design does not fit. |
ExecutionTimeout |
Limits how long the conversion process may run. | Increase for slow pages, but keep an upper bound for request safety. |
CustomArgs |
Adds wkhtmltoimage command-line switches. | Use only options supported by the installed renderer. |
ToolPath |
Points to the directory containing the executable. | Set this when binaries are outside the application’s default location. |
WkHtmlToImageExeName |
Changes the executable file name. | Useful when packaging a platform-specific binary under a custom name. |
ProcessPriority |
Controls child-process priority. | Use carefully on shared servers so image jobs do not starve other work. |
For example, this configuration asks the renderer to continue when a media request fails:
var converter = new HtmlToImageConverter
{
Width = 1200,
Height = 800,
ExecutionTimeout = 90000,
CustomArgs = " --load-media-error-handling ignore "
};
byte[] bytes = converter.GenerateImageFromFile(
"https://example.com/dashboard",
ImageFormat.Png
);
File.WriteAllBytes("dashboard.png", bytes);
The vendor documents --load-media-error-handling ignore for cases where output can still be generated despite missing external media. It does not make an inaccessible image appear; it lets conversion continue.
5. Add CSS, JavaScript, images, and SVG safely
Inline CSS is the most predictable option. External stylesheets and scripts must be publicly reachable or available from the local filesystem. Authentication-protected assets may fail unless the renderer can receive the required credentials through supported command-line options.
The underlying engine can render floating elements, images, JavaScript, and SVG charts, but it is based on QtWebKit 4.8. The vendor explicitly warns that modern CSS3 features such as flexbox and grid, plus ES2015 JavaScript, are not supported reliably. When a layout depends on current browser features, rewrite the critical styles using older CSS techniques or use a modern browser-based renderer.
<style>
/* More compatible than relying on CSS grid */
.column { display: inline-block; vertical-align: top; width: 48%; }
</style>
For deterministic output, wait for required content before converting, keep animations disabled, and avoid layouts that change after an indefinite timer. If JavaScript populates the page, verify that it completes within ExecutionTimeout.
6. Deployment on Windows, Linux, macOS, Docker, and modern .NET
The standard package starts wkhtmltoimage as a separate process. That means deployment must include a compatible executable, native dependencies, filesystem access, and permission to launch processes. Shared ASP.NET hosting, UWP or universal apps, and mobile environments may block one or more of these requirements.
For Linux, macOS, Docker, and modern .NET 6/.NET 8+ applications, NReco directs users to NReco.ImageGenerator.LT. The C# API is the same, but the wkhtmltoimage binary must be deployed separately. Treat the executable as part of your deployment artifact and validate it in the same container or host image used in production.
- Choose the package that matches your target platform.
- Place the renderer binary where the application can execute it.
- Set
ToolPathif the binary is not discovered automatically. - Run a conversion during deployment verification.
- Log the input type, elapsed time, exit errors, and output byte count.
Do not assume that a conversion working on a developer workstation will work in a locked-down web process. Process creation, font availability, network egress, and file permissions all affect the result.
7. Or skip the browser setup
If you need a screenshot service instead of packaging wkhtmltoimage, ScreenshotNeo accepts one GET request and returns a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for the complete parameter list.

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', bytes);
ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Available controls include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper size and margins, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, custom headers and cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs, and a usage API. Every feature is included on every plan. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
8. Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Executable not found | wkhtmltoimage is missing or outside the search path. | Deploy the binary and set ToolPath or WkHtmlToImageExeName. |
| Process starts locally but fails on the server | Child-process execution is blocked or permissions differ. | Allow process creation, grant execute permission, or move rendering to a worker/service. |
| Blank or incomplete image | Resources are unreachable, JavaScript has not finished, or the timeout is too short. | Use absolute resource URLs, increase ExecutionTimeout, and inspect renderer errors. |
| Missing images or CSS | Relative paths resolve incorrectly or network requests fail. | Use absolute URLs or correct the base path; optionally add --load-media-error-handling ignore when partial output is acceptable. |
| Modern layout is broken | QtWebKit 4.8 lacks modern CSS and JavaScript support. | Simplify critical CSS or use a current Chromium-based capture service. |
| Fonts differ between environments | The target machine does not have the same fonts installed. | Install required fonts in the host/container and verify font licensing. |
| Conversion hangs | A page waits forever on JavaScript, network, or an unresolved resource. | Set a finite timeout, remove long-running scripts, and block unnecessary resources. |
| Permission or licensing concern | The deployment redistributes the component or serves a SaaS. | Review NReco’s current license terms; external redistribution, multiple deployments, and SaaS require a commercial license according to the vendor. |
9. Performance, reliability, and cost considerations
Process overhead
Each conversion involves a child process and browser-style page loading. Reuse a configured converter where safe, queue bursts through a worker, and avoid unbounded parallel process creation. Set explicit dimensions so very large pages do not consume unexpected memory.
Network and page stability
Remote pages add DNS, TLS, server latency, redirects, and third-party resource failures. For repeatable output, self-host critical assets, use stable URLs, and record the source URL and conversion timestamp. A cache keyed by URL and template version can reduce repeated work.
Output format
PNG is generally appropriate for text-heavy interfaces and transparency. JPEG is usually smaller for photographs but introduces compression artifacts. BMP is available through the API but is rarely suitable for web delivery because files are large.
Licensing cost
The official FAQ says free use covers a single-deployment website, intranet or extranet, or an application used internally by a company. External redistribution, multiple deployments, and SaaS deployments require a commercial license. The vendor’s enterprise pack page listed $99 when crawled, but pricing can change, so verify the current amount before budgeting.
Hosted capture cost
ScreenshotNeo bills only clean shots. Failed loads, bot checks, blank pages, timeouts, and cache hits are free, which can make automated capture spend easier to control when target pages are unreliable. The free allowance is 1,000 screenshots per month with no card; paid plans begin at $5 for 3,000.
10. Production checklist
- Pin the NReco package and renderer version used by your deployment.
- Confirm the executable runs under the production service account.
- Set width, height, zoom, and a finite execution timeout.
- Test pages with missing images, redirects, slow scripts, and authentication.
- Verify fonts and locale-specific content on the target host.
- Log conversion duration, exceptions, output size, and source URL.
- Limit concurrent conversions and clean up temporary files.
- Review NReco licensing before redistribution or SaaS use.
- Use a modern browser capture service when the page depends on flexbox, grid, or ES2015 JavaScript.
FAQ
Can NReco.ImageGenerator convert a remote webpage?
Yes. Use GenerateImageFromFile with a URL, provided the renderer can reach the page and its resources.
Which image formats are supported?
The documented formats are BMP, JPEG, and PNG.
Does it use Chromium?
No. NReco.ImageGenerator wraps wkhtmltoimage, which is based on QtWebKit 4.8.
Why does a flexbox page render incorrectly?
QtWebKit 4.8 does not support many modern CSS3 features. Rewrite the critical layout with compatible CSS or choose a modern renderer.
Can I use it in a SaaS product?
The vendor’s FAQ says SaaS, multiple deployments, and external redistribution require a commercial license. Check the current terms before shipping.
When should I use ScreenshotNeo?
Use it when you want an HTTP API, clean captures with consent UI removed, MCP tools for AI agents, and no renderer executable to deploy.


