Table of Contents

Class PdfGenerator

Namespace
CobaltPdf
Assembly
CobaltPdf.dll

Provides functionality for generating PDF documents from HTML content or URLs.

public class PdfGenerator : IAsyncDisposable
Inheritance
PdfGenerator
Implements
Inherited Members

Remarks

Supports both isolated (dedicated browser instance) and pooled (shared browser pool) execution modes. Instances of this class are configured using a fluent API and must be disposed asynchronously after use.

Methods

AddCookie(string, string, string?, string)

Adds a browser cookie to the request context.

public PdfGenerator AddCookie(string name, string value, string? domain = null, string path = "/")

Parameters

name string
value string
domain string
path string

Returns

PdfGenerator

AddLocalStorage(string, string)

Adds a key-value pair to the browser's Local Storage before rendering.

public PdfGenerator AddLocalStorage(string key, string value)

Parameters

key string
value string

Returns

PdfGenerator

AddSessionStorage(string, string)

Adds a key-value pair to the browser's Session Storage before rendering.

public PdfGenerator AddSessionStorage(string key, string value)

Parameters

key string
value string

Returns

PdfGenerator

DisposeAsync()

Performs asynchronous cleanup of resources used by the PdfGenerator.

public ValueTask DisposeAsync()

Returns

ValueTask

A ValueTask representing the asynchronous dispose operation.

Remarks

This method ensures that any active browser leases are returned to the pool and that transient Playwright processes are terminated cleanly to prevent memory leaks.

RenderHtmlAsPdfAsync(string, CancellationToken)

Executes the generation process by rendering the provided HTML string.

public Task<PdfDocument> RenderHtmlAsPdfAsync(string html, CancellationToken cancellationToken = default)

Parameters

html string

The raw HTML content to render as a PDF.

cancellationToken CancellationToken

Optional token to cancel the render.

Returns

Task<PdfDocument>

A PdfDocument containing the generated binary data.

RenderHtmlFileAsPdfAsync(string, CancellationToken)

Reads an HTML file from disk and renders it as a PDF.

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 binary data.

Exceptions

FileNotFoundException

Thrown when the file does not exist.

RenderUrlAsPdfAsync(string, CancellationToken)

Executes the generation process by navigating to the specified URL.

public Task<PdfDocument> RenderUrlAsPdfAsync(string url, CancellationToken cancellationToken = default)

Parameters

url string

The fully qualified web address to render.

cancellationToken CancellationToken

Optional token to cancel the render.

Returns

Task<PdfDocument>

A PdfDocument containing the generated binary data.

WithCspBypass(bool)

Enables or disables the bypass of the page's Content Security Policy (CSP).

public PdfGenerator WithCspBypass(bool enable)

Parameters

enable bool

Returns

PdfGenerator

WithCustomJS(string)

Injects custom JavaScript to be executed on the page. Calling this multiple times will overwrite the previous script.

public PdfGenerator WithCustomJS(string script)

Parameters

script string

Returns

PdfGenerator

WithFonts(string)

Configures a local directory to search for custom fonts during rendering.

public PdfGenerator WithFonts(string path)

Parameters

path string

Returns

PdfGenerator

WithFooter(string)

Sets the HTML template or file path for the PDF footer.

public PdfGenerator WithFooter(string pathOrTemplate)

Parameters

pathOrTemplate string

Returns

PdfGenerator

WithGrayscale()

Enables grayscale rendering for the PDF.

public PdfGenerator WithGrayscale()

Returns

PdfGenerator

WithHeader(string)

Sets the HTML template or file path for the PDF header.

public PdfGenerator WithHeader(string pathOrTemplate)

Parameters

pathOrTemplate string

Returns

PdfGenerator

WithLandscape()

Sets the PDF orientation to landscape.

public PdfGenerator WithLandscape()

Returns

PdfGenerator

WithLazyLoadPages(int, TimeSpan?, TimeSpan?)

Scrolls through a specific number of pages to trigger lazy-loading.

public PdfGenerator WithLazyLoadPages(int pageCount, TimeSpan? delay = null, TimeSpan? timeout = null)

Parameters

pageCount int

Number of viewports to scroll.

delay TimeSpan?

Time to wait at each step. Default is 200ms.

timeout TimeSpan?

Maximum time to wait for the entire scroll process. Default is 30s.

Returns

PdfGenerator

WithMargins(MarginOptions)

Sets the page margins for the rendered PDF. Defaults to 1 cm on all sides if not called.

public PdfGenerator WithMargins(MarginOptions margins)

Parameters

margins MarginOptions

Returns

PdfGenerator

WithMediaType(CssMediaType)

Sets the CSS media type to emulate during rendering (e.g., Screen or Print).

public PdfGenerator WithMediaType(CssMediaType type)

Parameters

type CssMediaType

Returns

PdfGenerator

WithMetadata(Action<MetadataOptions>)

Sets descriptive metadata (title, author, subject, keywords, creator, producer) that will be embedded in the PDF's Information Dictionary.

public PdfGenerator WithMetadata(Action<MetadataOptions> configure)

Parameters

configure Action<MetadataOptions>

Returns

PdfGenerator

WithPageRanges(string)

Restricts the output PDF to the specified page ranges.

public PdfGenerator WithPageRanges(string ranges)

Parameters

ranges string

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

Returns

PdfGenerator

WithPageSize(string, string)

Sets custom page dimensions, overriding the paper format.

public PdfGenerator 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

PdfGenerator

WithPaperFormat(string)

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

public PdfGenerator WithPaperFormat(string format)

Parameters

format string

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

Returns

PdfGenerator

WithPrintBackground(bool)

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

public PdfGenerator WithPrintBackground(bool enable = true)

Parameters

enable bool

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

Returns

PdfGenerator

WithReloadAfterStorage()

Requests a page reload after localStorage and sessionStorage values have been injected on the initial page load.

public PdfGenerator WithReloadAfterStorage()

Returns

PdfGenerator

WithScale(float)

Sets the scale factor for PDF content (0.1 – 2.0). Values below 1.0 shrink the content.

public PdfGenerator WithScale(float scale)

Parameters

scale float

A value between 0.1 and 2.0.

Returns

PdfGenerator

WithWaitStrategy(WaitOptions)

Configures the strategy used to determine when the page is ready for PDF rendering. Use this to handle asynchronous content by waiting for a fixed duration or a specific event.

public PdfGenerator WithWaitStrategy(WaitOptions strategy)

Parameters

strategy WaitOptions

Returns

PdfGenerator

Remarks

Note: This is an assignment; if called multiple times, the last call in the chain wins.

Supported Strategies:

  • Network IdleThe default. Waits until there are no network requests for at least 500ms.
  • Fixed DelayWaits for a specific TimeSpan (e.g., WaitOptions.ForDelay(TimeSpan.FromSeconds(5))).
  • CSS/JS PollingWaits for a CSS selector to appear or a JS expression to return true.
  • Manual Signal The most robust method for complex apps. Use WaitOptions.ForSignal(timeout) and call window.cobaltNotifyRender() inside your WithCustomJS(string) script to manually trigger the render once your logic is complete.