Table of Contents

Class CobaltEngine

Namespace
CobaltPdf
Assembly
CobaltPdf.dll

The main PDF renderer for CobaltPdf. 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

The engine is backed by a shared browser pool. Browsers are kept warm between requests and recycled automatically — no setup needed per call.

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 behaviour for browser console messages.

public static BrowserLoggingMode LoggingMode { get; set; }

Property Value

BrowserLoggingMode

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 browser 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 browser pool with a fixed maximum size. All other settings remain at their defaults (including platform-safe ExtraArgs).

public static void Configure(int maxSize)

Parameters

maxSize int

Maximum number of concurrent browser instances. Must be ≥ 1.

Exceptions

InvalidOperationException

Thrown if called after the pool has already started.

Configure(int, int)

Configures the global browser pool with explicit minimum and maximum sizes. All other settings remain at their defaults (including platform-safe ExtraArgs).

public static void Configure(int minSize, int maxSize)

Parameters

minSize int

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

maxSize int

Maximum number of concurrent browser instances. Must be ≥ 1.

Exceptions

InvalidOperationException

Thrown if called after the pool has already started.

PreWarmAsync()

Pre-warms the browser pool, launching MinSize browsers immediately. Call after Configure(Action<PoolOptions>) to eliminate first-render latency.

public static Task PreWarmAsync()

Returns

Task

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 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 Chromium 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

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

Returns

CobaltEngine

WithEncryption(PdfEncryptionOptions)

Password-protects the output PDF.

public CobaltEngine WithEncryption(PdfEncryptionOptions encryption)

Parameters

encryption PdfEncryptionOptions

Returns

CobaltEngine

WithFonts(string)

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

public CobaltEngine WithFonts(string directoryPath)

Parameters

directoryPath string

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

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

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>

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 Playwright 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

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

Returns

CobaltEngine