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
LoggingMode
Gets or sets the logging behaviour for browser console messages.
public static BrowserLoggingMode LoggingMode { get; set; }
Property Value
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 browser 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 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
maxSizeintMaximum 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
minSizeintMinimum number of browsers to keep warm. Must be ≥ 0 and ≤
maxSize.maxSizeintMaximum 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
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 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 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
WithCspBypass(bool)
Enables or disables Content Security Policy bypass.
public CobaltEngine WithCspBypass(bool enable = true)
Parameters
enablebool
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
scriptstring
Returns
WithEncryption(PdfEncryptionOptions)
Password-protects the output PDF.
public CobaltEngine WithEncryption(PdfEncryptionOptions encryption)
Parameters
encryptionPdfEncryptionOptions
Returns
WithFonts(string)
Specifies a local directory to load custom fonts from during rendering.
public CobaltEngine WithFonts(string directoryPath)
Parameters
directoryPathstring
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
htmlOrPathstring
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
htmlOrPathstring
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>
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 Playwright 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
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
watermarkWatermarkOptions