Class CobaltEngine
The main PDF renderer for CobaltPdf.WebKit. Create one instance and call fluent methods to configure each render, finishing with RenderUrlAsPdfAsync(string, CancellationToken) or RenderHtmlAsPdfAsync(string, CancellationToken).
public sealed class CobaltEngine
- Inheritance
-
CobaltEngine
- Inherited Members
Examples
// One-time startup
CobaltEngine.Configure(o => { o.MinSize = 2; o.MaxSize = 8; });
// Per-request — simple
var renderer = new CobaltEngine();
var pdf = await renderer.RenderUrlAsPdfAsync("https://example.com");
pdf.SaveAs("output.pdf");
// Per-request — with options
var pdf = await renderer
.WithLandscape()
.AddCookie("session", "abc123")
.RenderUrlAsPdfAsync("https://example.com");
Remarks
API surface and call patterns are identical to the Chromium-based
CobaltPdf.CobaltEngine — uninstall CobaltPDF, install
CobaltPDF.WebKit, and your existing fluent code compiles and runs
unchanged.
On Linux each render runs as an inline WebKitGTK subprocess from a portable bundle the library provisions automatically on first use. On Windows it dispatches into WSL when available; a Docker fallback can be forced via ForceDocker. In Debug builds on Windows/macOS without a backend installed, the engine returns a clearly labelled placeholder PDF instead of throwing (controlled by StubModeOnWindows).
Properties
BrowserLogPath
Gets or sets the path where browser logs are written when LoggingMode includes File.
public static string BrowserLogPath { get; set; }
Property Value
LoggingMode
Gets or sets the logging behavior for browser-subprocess and page-console messages.
public static BrowserLoggingMode LoggingMode { get; set; }
Property Value
Remarks
Defaults to None — silent unless you opt
in — matching the Chromium-based CobaltPDF edition exactly, so the library
never writes to your console uninvited. Set to
Console to surface render warnings, page
console.log messages, and pikepdf chatter on stdout; or to
File / Both
to route logs to disk via BrowserLogPath with daily rotation.
OnBrowserLog
Optional callback invoked for every browser console message.
public static Action<string>? OnBrowserLog { get; set; }
Property Value
RetainedLogCount
Number of rotated log files to retain. Default is 7.
public static int RetainedLogCount { get; set; }
Property Value
Methods
AddCookie(string, string, string?, string)
Adds a cookie to the browser context for this render.
If domain is omitted, it is inferred automatically from the
final URL after any HTTP redirects.
public CobaltEngine AddCookie(string name, string value, string? domain = null, string path = "/")
Parameters
namestringCookie name.
valuestringCookie value.
domainstringOptional. Domain scope (e.g.
".example.com"). Leave null to have CobaltPdf infer it from the rendered page URL.pathstringCookie path. Defaults to
"/".
Returns
AddLocalStorage(string, string)
Injects a key/value pair into localStorage before the page loads.
public CobaltEngine AddLocalStorage(string key, string value)
Parameters
Returns
AddSessionStorage(string, string)
Injects a key/value pair into sessionStorage before the page loads.
public CobaltEngine AddSessionStorage(string key, string value)
Parameters
Returns
Configure(Action<PoolOptions>)
Configures the global worker pool. Call once at application startup, before any render.
public static void Configure(Action<PoolOptions> configure)
Parameters
configureAction<PoolOptions>Action to apply settings to PoolOptions.
Exceptions
- InvalidOperationException
Thrown if called after the pool has already started.
Configure(int)
Configures the global worker pool with a fixed maximum size. All other settings remain at their defaults.
public static void Configure(int maxSize)
Parameters
maxSizeintMaximum number of concurrent worker instances. Must be ≥ 1.
Exceptions
- InvalidOperationException
Thrown if called after the pool has already started.
Configure(int, int)
Configures the global worker pool with explicit minimum and maximum sizes. All other settings remain at their defaults.
public static void Configure(int minSize, int maxSize)
Parameters
minSizeintMinimum number of workers to keep warm. Must be ≥ 0 and ≤
maxSize.maxSizeintMaximum number of concurrent worker instances. Must be ≥ 1.
Exceptions
- InvalidOperationException
Thrown if called after the pool has already started.
PreWarmAsync(CancellationToken)
Eagerly provisions whichever backend this host will use, AND warms up MinSize worker processes so the first user request doesn't pay any cold-start cost.
public static Task PreWarmAsync(CancellationToken cancellationToken = default)
Parameters
cancellationTokenCancellationToken
Returns
Remarks
- Linux → fetch and extract the inline WebKit bundle, then spawn MinSize render workers.
- Windows + WSL → same, but the workers run inside the WSL distro.
- Windows / macOS + Docker →
docker pullthe dev image (no pooled workers). - Stub mode → nothing to warm.
Safe — and recommended — to call from Program.cs startup. When
no backend is available and stub mode is off, throws an
InvalidOperationException whose message lists every
backend tried and the exact next step to enable each one.
RenderHtmlAsPdfAsync(string, CancellationToken)
Renders the supplied HTML string as a PDF and returns the result. Any fluent options set before this call are consumed and reset automatically.
public Task<PdfDocument> RenderHtmlAsPdfAsync(string html, CancellationToken cancellationToken = default)
Parameters
htmlstringRaw HTML content to render.
cancellationTokenCancellationTokenOptional token to cancel the render.
Returns
- Task<PdfDocument>
A PdfDocument containing the generated PDF bytes.
RenderHtmlFileAsPdfAsync(string, CancellationToken)
Reads an HTML file from disk and renders it as a PDF. Any fluent options set before this call are consumed and reset automatically.
public Task<PdfDocument> RenderHtmlFileAsPdfAsync(string filePath, CancellationToken cancellationToken = default)
Parameters
filePathstringAbsolute or relative path to a
.htmlfile on disk.cancellationTokenCancellationTokenOptional token to cancel the render.
Returns
- Task<PdfDocument>
A PdfDocument containing the generated PDF bytes.
Exceptions
- FileNotFoundException
Thrown when
filePathdoes not exist.
RenderUrlAsPdfAsync(string, CancellationToken)
Renders the page at url as a PDF and returns the result.
Any fluent options set before this call are consumed and reset automatically.
public Task<PdfDocument> RenderUrlAsPdfAsync(string url, CancellationToken cancellationToken = default)
Parameters
urlstringFully qualified URL to render (e.g.
https://example.com).cancellationTokenCancellationTokenOptional token to cancel the render.
Returns
- Task<PdfDocument>
A PdfDocument containing the generated PDF bytes.
SetLicense(string)
Activates a CobaltPdf.WebKit license key.
public static void SetLicense(string key)
Parameters
keystringThe RSA-signed license string provided at purchase.
Exceptions
- InvalidOperationException
Thrown if the key is invalid, forged, or expired.
ShutdownAsync()
Gracefully shuts down the pool and terminates all worker processes.
After calling this method, Configure(Action<PoolOptions>) may be called again to
reconfigure and restart the pool (e.g. for integration tests or benchmarks).
Call on application shutdown (e.g. IHostApplicationLifetime.ApplicationStopping).
public static Task ShutdownAsync()
Returns
WithCspBypass(bool)
Enables or disables Content Security Policy bypass.
public CobaltEngine WithCspBypass(bool enable = true)
Parameters
enablebooltrueto bypass CSP (required when injecting custom fonts or scripts into strict sites).
Returns
WithCustomJS(string)
Executes custom JavaScript on the page before rendering.
Use window.cobaltNotifyRender() inside the script when combined with
WithWaitStrategy(WaitOptions) using ForSignal(TimeSpan).
public CobaltEngine WithCustomJS(string script)
Parameters
scriptstringThe JavaScript source to evaluate after page load.
Returns
WithEncryption(PdfEncryptionOptions)
Password-protects the output PDF.
public CobaltEngine WithEncryption(PdfEncryptionOptions encryption)
Parameters
encryptionPdfEncryptionOptionsEncryption settings — user/owner passwords plus allowed actions.
Returns
WithFonts(string)
Specifies a local directory to load custom fonts from during rendering.
public CobaltEngine WithFonts(string directoryPath)
Parameters
directoryPathstringAbsolute or relative path to a directory containing font files (TTF, OTF, WOFF, WOFF2).
Returns
Exceptions
- DirectoryNotFoundException
Thrown if the directory does not exist.
WithFooter(string)
Sets the PDF footer from an HTML string or a file path.
public CobaltEngine WithFooter(string htmlOrPath)
Parameters
htmlOrPathstringRaw HTML, or a path to a
.htmlfile whose contents will be loaded.
Returns
WithGrayscale()
Enables grayscale rendering.
public CobaltEngine WithGrayscale()
Returns
WithHeader(string)
Sets the PDF header from an HTML string or a file path.
public CobaltEngine WithHeader(string htmlOrPath)
Parameters
htmlOrPathstringRaw HTML, or a path to a
.htmlfile whose contents will be loaded.
Returns
WithHttpHeader(string, string)
Adds or overwrites a single HTTP request header sent by the browser for every request during this render (navigation and all sub-resources). Call multiple times to set multiple headers.
public CobaltEngine WithHttpHeader(string name, string value)
Parameters
Returns
WithHttpHeaders(IDictionary<string, string>)
Merges a dictionary of HTTP request headers into the headers sent by the browser for every request during this render. Existing keys are overwritten.
public CobaltEngine WithHttpHeaders(IDictionary<string, string> headers)
Parameters
headersIDictionary<string, string>Key/value pairs to add or overwrite.
Returns
WithLandscape()
Sets the output orientation to landscape.
public CobaltEngine WithLandscape()
Returns
WithLazyLoadPages(int, TimeSpan?, TimeSpan?)
Scrolls the page by pageCount viewports before rendering,
triggering any lazy-loaded images or infinite-scroll content.
public CobaltEngine WithLazyLoadPages(int pageCount, TimeSpan? delay = null, TimeSpan? timeout = null)
Parameters
pageCountintNumber of viewport-heights to scroll.
delayTimeSpan?Pause between each scroll step. Default is 200 ms.
timeoutTimeSpan?Maximum time to wait for content to load after scrolling. Default is 10 s.
Returns
WithMargins(MarginOptions)
Sets the page margins for the rendered PDF. Defaults to 1 cm on all sides if not called.
public CobaltEngine WithMargins(MarginOptions margins)
Parameters
marginsMarginOptions
Returns
Examples
renderer.WithMargins(MarginOptions.None)
renderer.WithMargins(new MarginOptions(15, MarginUnit.Millimeters))
renderer.WithMargins(new MarginOptions(top: 10, right: 15, bottom: 10, left: 15, MarginUnit.Millimeters))
WithMediaType(CssMediaType)
Sets the CSS media type to emulate (e.g. Print or Screen).
public CobaltEngine WithMediaType(CssMediaType type)
Parameters
typeCssMediaType
Returns
WithMetadata(Action<MetadataOptions>)
Sets descriptive metadata (title, author, subject, etc.) embedded in the PDF.
public CobaltEngine WithMetadata(Action<MetadataOptions> configure)
Parameters
configureAction<MetadataOptions>Action that mutates the MetadataOptions instance attached to this render.
Returns
WithPageRanges(string)
Restricts the output PDF to the specified page ranges.
public CobaltEngine WithPageRanges(string ranges)
Parameters
rangesstringComma-separated page ranges, e.g.
"1-3","1,4,7".
Returns
WithPageSize(string, string)
Sets custom page dimensions, overriding the paper format.
public CobaltEngine WithPageSize(string width, string height)
Parameters
widthstringCSS width string, e.g.
"8.5in","200mm".heightstringCSS height string, e.g.
"11in","297mm".
Returns
WithPaperFormat(string)
Sets the paper format (size) for the rendered PDF.
Defaults to "A4" if not called.
public CobaltEngine WithPaperFormat(string format)
Parameters
formatstringA paper format string, e.g.
"A4","A3","Letter","Legal","Tabloid".
Returns
WithPrintBackground(bool)
Enables or disables printing of CSS background graphics (colors, images).
public CobaltEngine WithPrintBackground(bool enable = true)
Parameters
enablebooltrueto print backgrounds (default);falseto suppress them.
Returns
WithReloadAfterStorage()
Requests a page reload after localStorage and sessionStorage values have been injected on the initial page load. This is useful for React, Angular, and other SPA frameworks that read storage values only during their initialisation lifecycle.
public CobaltEngine WithReloadAfterStorage()
Returns
Remarks
The reload happens once, regardless of how many storage items are added. If inferred-domain cookies also trigger a reload, only one reload is performed.
WithScale(float)
Sets the scale factor for PDF content (0.1 – 2.0). Values below 1.0 shrink the content.
public CobaltEngine WithScale(float scale)
Parameters
scalefloatA value between
0.1and2.0.
Returns
WithUserAgent(string)
Overrides the browser's User-Agent string for this render. Useful for spoofing mobile devices or bypassing bot-detection on sites that check the UA.
public CobaltEngine WithUserAgent(string userAgent)
Parameters
userAgentstringThe full User-Agent string to send with every HTTP request.
Returns
WithViewportSize(int)
Sets the render viewport width (CSS px), controlling which responsive layout a site serves. By default the engine uses the printable width of the paper (Chrome-like). Pass e.g. 1280 for a full desktop layout, or ~390 to capture a site's mobile layout.
public CobaltEngine WithViewportSize(int width)
Parameters
widthintViewport width in CSS pixels.
Returns
WithViewportSize(int, int)
Sets the render viewport width and a minimum height (both CSS px). The engine still uses a tall internal viewport for lazy-load when the supplied height is smaller, so lazy images on long pages still load.
public CobaltEngine WithViewportSize(int width, int height)
Parameters
Returns
WithWaitStrategy(WaitOptions)
Sets the strategy used to decide when the page is ready to render. Defaults to network idle if not called.
public CobaltEngine WithWaitStrategy(WaitOptions strategy)
Parameters
strategyWaitOptions
Returns
Examples
renderer.WithWaitStrategy(WaitOptions.ForDelay(TimeSpan.FromSeconds(2)))
renderer.WithWaitStrategy(WaitOptions.ForSelector("#content-loaded"))
renderer.WithWaitStrategy(WaitOptions.ForSignal(TimeSpan.FromSeconds(10)))
WithWatermark(WatermarkOptions)
Applies a watermark overlay to every page of the output PDF.
public CobaltEngine WithWatermark(WatermarkOptions watermark)
Parameters
watermarkWatermarkOptionsThe watermark to apply. Build with WithText(string, WatermarkStyle) or by constructing manually.
Returns
WithoutPostProcessing(bool)
Return the engine's raw PDF output, skipping the post-processing pipeline (font subsetting, image re-encoding, font deduplication, metadata stamping). Renders are faster and peak memory drops by ~30 MB per render — but output files are ~70 % larger because fonts are embedded whole and images are not re-compressed.
public CobaltEngine WithoutPostProcessing(bool enable = true)
Parameters
enablebooltrue(default) to skip post-processing;falseto restore the full pipeline.
Returns
Remarks
Use on memory-constrained hosts (small Azure plans, tight containers) when the PDF is transient — a preview, an in-memory stream — and bytes-on-disk don't matter.
Side-effects: WithWatermark(WatermarkOptions), WithEncryption(PdfEncryptionOptions), WithMetadata(Action<MetadataOptions>), OptimizeImages and OptimizeFonts are all implemented BY the post-processing pipeline, so they are ignored while it is skipped.