Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 28 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ using Gotenberg.Sharp.API.Client;
using Gotenberg.Sharp.API.Client.Domain.Builders;
using Gotenberg.Sharp.API.Client.Domain.Builders.Faceted;
using Gotenberg.Sharp.API.Client.Domain.Requests.Facets; // For Cookie, etc.
using Gotenberg.Sharp.API.Client.Domain.ValueObjects; // For ScreenshotFormat, etc.
```

### HTML To PDF
Expand Down Expand Up @@ -529,27 +530,41 @@ public async Task<Stream> FastConversion()
}
```

### Wait For Selector & Emulated Media Features
*Wait for a DOM element and emulate CSS media features like dark mode:*
### Screenshot from HTML
*Capture a screenshot of HTML content as PNG, JPEG, or WebP:*

```csharp
public async Task<Stream> CreateWithChromiumFeatures()
public async Task<Stream> ScreenshotHtml()
{
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody("<html><body><div id='app'>Ready</div></body></html>"))
.SetConversionBehaviors(b => b
.SetWaitForSelector("#app")
.AddEmulatedMediaFeature("prefers-color-scheme", "dark")
.SetFailOnHttpStatusCodes(499, 599)
.FailOnResourceLoadingFailed()
.AddIgnoreResourceHttpStatusDomains("cdn.example.com"))
.WithPageProperties(pp => pp.UseChromeDefaults());
var builder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody("<html><body><h1>Screenshot!</h1></body></html>"))
.WithScreenshotProperties(p => p
.SetSize(1280, 720)
.SetFormat(ScreenshotFormat.Png));

var request = builder.Build();
return await _sharpClient.HtmlToPdfAsync(request);
return await _sharpClient.ScreenshotHtmlAsync(request);
}
```

### Screenshot from URL
*Capture a screenshot of any URL:*

```csharp
public async Task<Stream> ScreenshotUrl()
{
var builder = new ScreenshotUrlRequestBuilder()
.SetUrl("https://example.com")
.WithScreenshotProperties(p => p
.SetSize(1024, 768)
.SetFormat(ScreenshotFormat.Jpeg)
.SetQuality(90)
.SetClip());

var request = builder.Build();
return await _sharpClient.ScreenshotUrlAsync(request);
}
```

### Custom Page Properties
*Fine-tune page dimensions and properties:*
Expand Down
85 changes: 85 additions & 0 deletions examples/Screenshot/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Gotenberg.Sharp.API.Client;
using Gotenberg.Sharp.API.Client.Domain.Builders;
using Gotenberg.Sharp.API.Client.Domain.ValueObjects;
using Gotenberg.Sharp.API.Client.Domain.Settings;
using Gotenberg.Sharp.API.Client.Infrastructure.Pipeline;

using Microsoft.Extensions.Configuration;

var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();

var options = new GotenbergSharpClientOptions();
config.GetSection(nameof(GotenbergSharpClient)).Bind(options);

var destinationDirectory = args.Length > 0 ? args[0] : Path.Combine(Directory.GetCurrentDirectory(), "output");
Directory.CreateDirectory(destinationDirectory);

var sharpClient = CreateClient(options);

// Screenshot from HTML
var htmlPath = await ScreenshotFromHtml(destinationDirectory, sharpClient);
Console.WriteLine($"HTML screenshot: {htmlPath}");

// Screenshot from URL
var urlPath = await ScreenshotFromUrl(destinationDirectory, sharpClient);
Console.WriteLine($"URL screenshot: {urlPath}");

static async Task<string> ScreenshotFromHtml(string destinationDirectory, GotenbergSharpClient sharpClient)
{
var builder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(@"
<html>
<body style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px;'>
<h1 style='color: white; font-family: sans-serif;'>Screenshot Demo</h1>
<p style='color: white;'>Captured with Gotenberg + GotenbergSharpApiClient</p>
</body>
</html>"))
.WithScreenshotProperties(p => p
.SetSize(1280, 720)
.SetFormat(ScreenshotFormat.Png));

await using var response = await sharpClient.ScreenshotHtmlAsync(builder);

var resultPath = Path.Combine(destinationDirectory, $"ScreenshotHtml-{DateTime.Now:yyyyMMddHHmmss}.png");
await using var file = File.Create(resultPath);
await response.CopyToAsync(file);
return resultPath;
}

static async Task<string> ScreenshotFromUrl(string destinationDirectory, GotenbergSharpClient sharpClient)
{
var builder = new ScreenshotUrlRequestBuilder()
.SetUrl("https://example.com")
.WithScreenshotProperties(p => p
.SetSize(1024, 768)
.SetFormat(ScreenshotFormat.Jpeg)
.SetQuality(90)
.SetClip());

await using var response = await sharpClient.ScreenshotUrlAsync(builder);

var resultPath = Path.Combine(destinationDirectory, $"ScreenshotUrl-{DateTime.Now:yyyyMMddHHmmss}.jpg");
await using var file = File.Create(resultPath);
await response.CopyToAsync(file);
return resultPath;
}

static GotenbergSharpClient CreateClient(GotenbergSharpClientOptions options)
{
var handler = new HttpClientHandler();
HttpMessageHandler effectiveHandler = handler;

if (!string.IsNullOrWhiteSpace(options.BasicAuthUsername) && !string.IsNullOrWhiteSpace(options.BasicAuthPassword))
effectiveHandler = new BasicAuthHandler(options.BasicAuthUsername, options.BasicAuthPassword) { InnerHandler = handler };

var httpClient = new HttpClient(effectiveHandler)
{
BaseAddress = options.ServiceUrl,
Timeout = options.TimeOut
};

return new GotenbergSharpClient(httpClient);
}
2 changes: 2 additions & 0 deletions examples/Screenshot/Screenshot.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<Project Sdk="Microsoft.NET.Sdk">
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright 2019-2026 Chris Mohan, Jaben Cargman
// and GotenbergSharpApiClient Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Gotenberg.Sharp.API.Client.Domain.Builders;

/// <summary>
/// Base builder for all Chromium screenshot requests. Provides screenshot properties,
/// conversion behaviors, and asset management shared across URL and HTML screenshot builders.
/// </summary>
public abstract class BaseScreenshotBuilder<TRequest, TBuilder>(TRequest request)
: BaseBuilder<TRequest, TBuilder>(request)
where TRequest : ScreenshotRequest
where TBuilder : BaseScreenshotBuilder<TRequest, TBuilder>
{
/// <summary>
/// Configures screenshot-specific properties (device dimensions, format, quality).
/// </summary>
public TBuilder WithScreenshotProperties(Action<ScreenshotPropertyBuilder> action)
{
if (action == null) throw new ArgumentNullException(nameof(action));

action(new ScreenshotPropertyBuilder(this.Request.ScreenshotProperties));

return (TBuilder)this;
}

/// <summary>
/// Configures Chromium rendering behaviors (wait conditions, cookies, headers, error handling).
/// </summary>
public TBuilder SetConversionBehaviors(Action<HtmlConversionBehaviorBuilder> action)
{
if (action == null) throw new ArgumentNullException(nameof(action));

action(new HtmlConversionBehaviorBuilder(this.Request.ConversionBehaviors));

return (TBuilder)this;
}

/// <summary>
/// Sets pre-configured conversion behaviors.
/// </summary>
public TBuilder SetConversionBehaviors(HtmlConversionBehaviors behaviors)
{
this.Request.ConversionBehaviors = behaviors ?? throw new ArgumentNullException(nameof(behaviors));

return (TBuilder)this;
}

/// <summary>
/// Adds embedded assets (images, fonts, CSS, JS) referenced by the HTML content.
/// </summary>
public TBuilder WithAssets(Action<AssetBuilder> action)
{
if (action == null) throw new ArgumentNullException(nameof(action));

this.Request.Assets ??= new AssetDictionary();

action(new AssetBuilder(this.Request.Assets));

return (TBuilder)this;
}

/// <summary>
/// Adds embedded assets asynchronously (e.g., from streams or files).
/// </summary>
public TBuilder WithAsyncAssets(Func<AssetBuilder, Task> asyncAction)
{
if (asyncAction == null) throw new ArgumentNullException(nameof(asyncAction));

this.Request.Assets ??= new AssetDictionary();

this.BuildTasks.Add(asyncAction(new AssetBuilder(this.Request.Assets)));

return (TBuilder)this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright 2019-2026 Chris Mohan, Jaben Cargman
// and GotenbergSharpApiClient Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Gotenberg.Sharp.API.Client.Domain.ValueObjects;

namespace Gotenberg.Sharp.API.Client.Domain.Builders.Faceted;

/// <summary>
/// Configures screenshot-specific properties (device dimensions, format, quality).
/// </summary>
public sealed class ScreenshotPropertyBuilder
{
private readonly ScreenshotProperties _properties;

internal ScreenshotPropertyBuilder(ScreenshotProperties properties)
{
_properties = properties;
}

public ScreenshotPropertyBuilder SetWidth(ScreenDimension width)
{
_properties.Width = width ?? throw new ArgumentNullException(nameof(width));
return this;
}

public ScreenshotPropertyBuilder SetWidth(int pixels)
{
return SetWidth(ScreenDimension.Create(pixels));
}

public ScreenshotPropertyBuilder SetHeight(ScreenDimension height)
{
_properties.Height = height ?? throw new ArgumentNullException(nameof(height));
return this;
}

public ScreenshotPropertyBuilder SetHeight(int pixels)
{
return SetHeight(ScreenDimension.Create(pixels));
}

public ScreenshotPropertyBuilder SetSize(int width, int height)
{
return SetWidth(width).SetHeight(height);
}

public ScreenshotPropertyBuilder SetClip(bool clip = true)
{
_properties.Clip = clip;
return this;
}

public ScreenshotPropertyBuilder SetFormat(ScreenshotFormat format)
{
_properties.Format = format;
return this;
}

public ScreenshotPropertyBuilder SetQuality(CompressionQuality quality)
{
_properties.Quality = quality ?? throw new ArgumentNullException(nameof(quality));
return this;
}

public ScreenshotPropertyBuilder SetQuality(int quality)
{
return SetQuality(CompressionQuality.Create(quality));
}

public ScreenshotPropertyBuilder SetOmitBackground(bool omit = true)
{
_properties.OmitBackground = omit;
return this;
}

public ScreenshotPropertyBuilder SetOptimizeForSpeed(bool optimize = true)
{
_properties.OptimizeForSpeed = optimize;
return this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2019-2026 Chris Mohan, Jaben Cargman
// and GotenbergSharpApiClient Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Gotenberg.Sharp.API.Client.Domain.Builders;

/// <summary>
/// Builds requests for capturing screenshots of HTML content using Chromium.
/// </summary>
public sealed class ScreenshotHtmlRequestBuilder()
: BaseScreenshotBuilder<ScreenshotHtmlRequest, ScreenshotHtmlRequestBuilder>(new ScreenshotHtmlRequest())
{
/// <summary>
/// Configures the HTML document content for the screenshot.
/// </summary>
public ScreenshotHtmlRequestBuilder AddDocument(Action<DocumentBuilder> action)
{
if (action == null) throw new ArgumentNullException(nameof(action));

this.Request.Content ??= new FullDocument();

action(new DocumentBuilder(this.Request.Content, _ => { }));

return this;
}

/// <summary>
/// Configures the HTML document content asynchronously.
/// </summary>
public ScreenshotHtmlRequestBuilder AddAsyncDocument(Func<DocumentBuilder, Task> asyncAction)
{
if (asyncAction == null) throw new ArgumentNullException(nameof(asyncAction));

this.Request.Content ??= new FullDocument();

this.BuildTasks.Add(asyncAction(new DocumentBuilder(this.Request.Content, _ => { })));

return this;
}
}
Loading
Loading