Recursive AI

Resize a live HTML viewport and set device pixel ratio in C#

OneRender is a free, open-source HTML and CSS rendering library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Call SetViewport(width, height, ratio) on the existing page to keep its form values.

Terminal
dotnet add package RecursiveAI.OneRender.Image

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneRender;
using OneRender.Image;
using OneRender.Interaction;
 
var page = InteractivePage.Create(
    "<input id='name' value='Draft'>",
    new HtmlPageOptions(
        FontProviders.CreateDefault()));
var input = page.FindElement("name");
page.SetValue(input, "Edited");
page.SetViewport(320, 180, 2);
Console.WriteLine(
    page.GetValue(page.FindElement("name")));
Text
Edited

The input keeps its edited value. The full program below shows the effect of 2×: a 320 × 180 CSS-pixel viewport produces a 640 × 360-pixel after.png.

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

The full program

C#
using OneRender;
using OneRender.Image;
using OneRender.Interaction;
using OneRender.Painting;
 
const string html = """
    <style>
      #card { width: 50vw; background: #dcecfb; padding: 8px }
      input { width: 100%; box-sizing: border-box }
      @media (max-width: 320px) and (min-resolution: 2dppx) {
        #card { background: #b9ecd3 }
      }
    </style>
    <div id="card"><input id="name" value="Draft"></div>
    """;
var page = InteractivePage.Create(html,
    new HtmlPageOptions(FontProviders.CreateDefault())
    { ViewportWidth = 480, ViewportHeight = 100 });
page.SetValue(page.FindElement("name"), "Edited");
Save("before.png");
page.SetViewport(320, 180, 2);
Save("after.png");
Console.WriteLine($"Input: {page.GetValue(page.FindElement("name"))}");
 
void Save(string path)
{
    double width = page.ViewportWidth;
    double height = page.ViewportHeight;
    float ratio = (float)page.DevicePixelRatio;
    var drawing = new DisplayList();
    page.Page.Paint(drawing);
    int pixelsWide = (int)Math.Ceiling(width * ratio);
    int pixelsHigh = (int)Math.Ceiling(height * ratio);
    var image = DisplayListRasterizer.Render(drawing, pixelsWide, pixelsHigh,
        new RasterOptions { DevicePixelRatio = ratio });
    File.WriteAllBytes(path, image.ToPng());
    Console.WriteLine($"{path}: {width}x{height} CSS px at {ratio}x"
        + $" -> {image.Width}x{image.Height} pixels");
}
Text
before.png: 480x100 CSS px at 1x -> 480x100 pixels
after.png: 320x180 CSS px at 2x -> 640x360 pixels
Input: Edited

The blue card becomes green when the width and resolution conditions both match. The input still reads “Edited”, not the markup’s initial value “Draft”.

A width or height below 1 CSS pixel, or a zero or negative ratio, throws ArgumentOutOfRangeException and leaves the viewport unchanged.

Variations

Handle separate window and display events. Replace SetViewport with these calls if the size and ratio arrive separately:

C#
page.Resize(360, 180);       // keeps the current ratio
page.SetDevicePixelRatio(2); // keeps the current size

The short answer

Call page.SetViewport(width, height, ratio) on the InteractivePage you already have. Pass dimensions in CSS pixels and the device pixel ratio separately. Then paint the current page and resize the target bitmap to match its new physical pixel dimensions.

How do I set the viewport size of an HTML render?

For an interactive page, Resize changes the CSS viewport size, SetDevicePixelRatio changes just the pixel ratio, and SetViewport changes both together. These methods configure OneRender’s viewport, not the operating system window. Use the window size your host reports in CSS pixels or convert from physical pixels first; otherwise the layout can pick a wide-screen breakpoint on a narrow high-density window.

The CSS viewport determines what vw means. In the example, 50vw is 240 CSS pixels before resizing and 160 after, not counting padding. OneRender rechecks media queries that depend on width, height, aspect ratio, orientation or resolution. The green card requires both a width of at most 320 CSS pixels and a resolution of at least 2 device pixels per CSS pixel.

What is a device pixel ratio?

Device pixel ratio is how many physical pixels cover one CSS pixel along an axis. At 2×, a box that’s 100 CSS pixels wide uses 200 bitmap pixels. When rasterizing, size the bitmap and pass the same ratio to RasterOptions.DevicePixelRatio. Increasing the bitmap dimensions without setting the rasterizer’s ratio doesn’t scale the drawing to fill that bitmap. A ratio change also affects snapping to pixel edges and may change layout if a resolution query changes which rules apply.

Will resizing the HTML viewport reset form fields?

Not when you resize the existing InteractivePage. The viewport documentation says the page keeps form values and selection, listeners and running animations. The example finds the same input after resizing and reads its current value rather than the initial value attribute. There are layout-dependent exceptions for interaction: a focused element that a media query hides loses focus, and the new scroll range can clamp a scroll position. Handle those as changes to the live page, not as a reason to reload the HTML.

All onerender recipes