Table of Contents

Class CobaltEngine

Namespace
CobaltPdf.WebKit
Assembly
CobaltPDF.WebKit.dll

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

string

LoggingMode

Gets or sets the logging behavior for browser-subprocess and page-console messages.

public static BrowserLoggingMode LoggingMode { get; set; }

Property Value

BrowserLoggingMode

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

Action<string>

RetainedLogCount

Number of rotated log files to retain. Default is 7.

public static int RetainedLogCount { get; set; }

Property Value

int

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

name string

Cookie name.

value string

Cookie value.

domain string

Optional. Domain scope (e.g. ".example.com"). Leave null to have CobaltPdf infer it from the rendered page URL.

path string

Cookie path. Defaults to "/".

Returns

CobaltEngine

AddLocalStorage(string, string)

Injects a key/value pair into localStorage before the page loads.

public CobaltEngine AddLocalStorage(string key, string value)

Parameters

key string
value string

Returns

CobaltEngine

AddSessionStorage(string, string)

Injects a key/value pair into sessionStorage before the page loads.

public CobaltEngine AddSessionStorage(string key, string value)

Parameters

key string
value string

Returns

CobaltEngine

Configure(Action<PoolOptions>)

Configures the global worker pool. Call once at application startup, before any render.

public static void Configure(Action<PoolOptions> configure)

Parameters

configure Action<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

maxSize int

Maximum 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

minSize int

Minimum number of workers to keep warm. Must be ≥ 0 and ≤ maxSize.

maxSize int

Maximum 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

cancellationToken CancellationToken

Returns

Task

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 pull the 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

html string

Raw HTML content to render.

cancellationToken CancellationToken

Optional 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

filePath string

Absolute or relative path to a .html file on disk.

cancellationToken CancellationToken

Optional token to cancel the render.

Returns

Task<PdfDocument>

A PdfDocument containing the generated PDF bytes.

Exceptions

FileNotFoundException

Thrown when filePath does 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

url string

Fully qualified URL to render (e.g. https://example.com).

cancellationToken CancellationToken

Optional 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

key string

The 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

Task

WithCspBypass(bool)

Enables or disables Content Security Policy bypass.

public CobaltEngine WithCspBypass(bool enable = true)

Parameters

enable bool

true to bypass CSP (required when injecting custom fonts or scripts into strict sites).

Returns

CobaltEngine

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

script string

The JavaScript source to evaluate after page load.

Returns

CobaltEngine

WithEncryption(PdfEncryptionOptions)

Password-protects the output PDF.

public CobaltEngine WithEncryption(PdfEncryptionOptions encryption)

Parameters

encryption PdfEncryptionOptions

Encryption settings — user/owner passwords plus allowed actions.

Returns

CobaltEngine

WithFonts(string)

Specifies a local directory to load custom fonts from during rendering.

public CobaltEngine WithFonts(string directoryPath)

Parameters

directoryPath string

Absolute or relative path to a directory containing font files (TTF, OTF, WOFF, WOFF2).

Returns

CobaltEngine

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

htmlOrPath string

Raw HTML, or a path to a .html file whose contents will be loaded.

Returns

CobaltEngine

WithGrayscale()

Enables grayscale rendering.

public CobaltEngine WithGrayscale()

Returns

CobaltEngine

WithHeader(string)

Sets the PDF header from an HTML string or a file path.

public CobaltEngine WithHeader(string htmlOrPath)

Parameters

htmlOrPath string

Raw HTML, or a path to a .html file whose contents will be loaded.

Returns

CobaltEngine

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

name string

Header name (e.g. "Authorization", "X-Api-Key").

value string

Header value.

Returns

CobaltEngine

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

headers IDictionary<string, string>

Key/value pairs to add or overwrite.

Returns

CobaltEngine

WithLandscape()

Sets the output orientation to landscape.

public CobaltEngine WithLandscape()

Returns

CobaltEngine

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

pageCount int

Number of viewport-heights to scroll.

delay TimeSpan?

Pause between each scroll step. Default is 200 ms.

timeout TimeSpan?

Maximum time to wait for content to load after scrolling. Default is 10 s.

Returns

CobaltEngine

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

margins MarginOptions

Returns

CobaltEngine

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

type CssMediaType

Returns

CobaltEngine

WithMetadata(Action<MetadataOptions>)

Sets descriptive metadata (title, author, subject, etc.) embedded in the PDF.

public CobaltEngine WithMetadata(Action<MetadataOptions> configure)

Parameters

configure Action<MetadataOptions>

Action that mutates the MetadataOptions instance attached to this render.

Returns

CobaltEngine

WithPageRanges(string)

Restricts the output PDF to the specified page ranges.

public CobaltEngine WithPageRanges(string ranges)

Parameters

ranges string

Comma-separated page ranges, e.g. "1-3", "1,4,7".

Returns

CobaltEngine

WithPageSize(string, string)

Sets custom page dimensions, overriding the paper format.

public CobaltEngine WithPageSize(string width, string height)

Parameters

width string

CSS width string, e.g. "8.5in", "200mm".

height string

CSS height string, e.g. "11in", "297mm".

Returns

CobaltEngine

WithPaperFormat(string)

Sets the paper format (size) for the rendered PDF. Defaults to "A4" if not called.

public CobaltEngine WithPaperFormat(string format)

Parameters

format string

A paper format string, e.g. "A4", "A3", "Letter", "Legal", "Tabloid".

Returns

CobaltEngine

WithPrintBackground(bool)

Enables or disables printing of CSS background graphics (colors, images).

public CobaltEngine WithPrintBackground(bool enable = true)

Parameters

enable bool

true to print backgrounds (default); false to suppress them.

Returns

CobaltEngine

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

CobaltEngine

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

scale float

A value between 0.1 and 2.0.

Returns

CobaltEngine

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

userAgent string

The full User-Agent string to send with every HTTP request.

Returns

CobaltEngine

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

width int

Viewport width in CSS pixels.

Returns

CobaltEngine

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

width int

Viewport width in CSS pixels.

height int

Minimum viewport height in CSS pixels.

Returns

CobaltEngine

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

strategy WaitOptions

Returns

CobaltEngine

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

watermark WatermarkOptions

The watermark to apply. Build with WithText(string, WatermarkStyle) or by constructing manually.

Returns

CobaltEngine

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

enable bool

true (default) to skip post-processing; false to restore the full pipeline.

Returns

CobaltEngine

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.