### Navigate to and Run DIExample
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the DIExample and runs it. This example demonstrates dependency injection setup with logging and Polly retry policy.
```bash
cd DIExample
dotnet run [output-directory]
```
--------------------------------
### Navigate to and Run PdfConvert Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the PdfConvert example and runs it. This example converts PDF files to PDF/A formats.
```bash
cd PdfConvert
dotnet run [source-directory] [output-directory]
```
--------------------------------
### Navigate to and Run UrlConvert Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the UrlConvert example and runs it. This example converts a URL to PDF with custom header and footer.
```bash
cd UrlConvert
dotnet run [output-directory]
```
--------------------------------
### Navigate to and Run HtmlConvert Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the HtmlConvert example and runs it. This example converts HTML to PDF with embedded assets.
```bash
cd HtmlConvert
dotnet run [output-directory]
```
--------------------------------
### Run Example with Custom Directories
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Demonstrates running an example, specifically PdfMerge, with custom source and output directories specified as command-line arguments.
```bash
cd PdfMerge
dotnet run C:\MyPdfs C:\Output
```
--------------------------------
### Navigate to and Run HtmlWithMarkdown Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the HtmlWithMarkdown example and runs it. This example converts HTML containing Markdown to PDF.
```bash
cd HtmlWithMarkdown
dotnet run [output-directory]
```
--------------------------------
### Navigate to and Run OfficeMerge Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the OfficeMerge example and runs it. This example merges Office documents into a single PDF.
```bash
cd OfficeMerge
dotnet run [source-directory] [output-directory]
```
--------------------------------
### Navigate to and Run Webhook Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the Webhook example and runs it. This example demonstrates webhook functionality for asynchronous PDF generation. Requires a webhook receiver API.
```bash
cd Webhook
dotnet run
```
--------------------------------
### Run Docker Compose for Basic Auth
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Starts a Gotenberg instance using Docker Compose with basic authentication enabled. This is a prerequisite for most examples.
```bash
docker-compose -f docker/docker-compose-basic-auth.yml up -d
```
--------------------------------
### Navigate to and Run PdfMerge Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the PdfMerge example and runs it. This example merges multiple PDF files into a single PDF.
```bash
cd PdfMerge
dotnet run [source-directory] [output-directory]
```
--------------------------------
### Install Gotenberg and Add NuGet Package
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Instructions for setting up Gotenberg via Docker and adding the GotenbergSharpApiClient NuGet package to your .NET project.
```bash
# Start Gotenberg (with optional timeout override)
docker run --name gotenberg --rm -p 3000:3000 \
gotenberg/gotenberg:latest \
gotenberg --api-timeout=1800s --log-level=debug
# Or with basic auth via docker-compose
docker-compose -f docker/docker-compose-basic-auth.yml up -d
# Credentials: testuser / testpass
# Add the package
dotnet add package Gotenberg.Sharp.Api.Client
```
--------------------------------
### Install GotenbergSharpApiClient Package
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/index.md
Use the dotnet CLI to add the GotenbergSharpApiClient package to your project.
```bash
dotnet add package Gotenberg.Sharp.Api.Client
```
--------------------------------
### Navigate to and Run UrlsToMergedPdf Example
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/examples/README.md
Changes directory to the UrlsToMergedPdf example and runs it. This example converts multiple URLs to PDFs and merges them. Requires an increased Gotenberg timeout.
```bash
cd UrlsToMergedPdf
dotnet run [output-directory]
```
--------------------------------
### Run Gotenberg with Docker
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Starts a Gotenberg container using Docker, exposing port 3000 and setting a custom API timeout and log level.
```bash
docker pull gotenberg/gotenberg:latest
docker run --name gotenberg --rm -p 3000:3000 gotenberg/gotenberg:latest gotenberg --api-timeout=1800s --log-level=debug
```
--------------------------------
### Run Gotenberg Docker Container
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/README.md
Start a Gotenberg Docker container, exposing port 3000 for the API to be accessible.
```bash
docker run --rm -p 3000:3000 gotenberg/gotenberg:latest
```
--------------------------------
### Merge Existing PDFs with GotenbergSharp
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Combines multiple existing PDF files into a single PDF document. This example demonstrates merging local files and also merging PDFs generated from URLs.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.PdfFormat;
var pdfFiles = Directory.GetFiles("./pdfs", "*.pdf")
.OrderBy(p => new FileInfo(p).CreationTime)
.Take(5)
.Select(p => KeyValuePair.Create(Path.GetFileName(p), File.ReadAllBytes(p)));
var mergeBuilder = new MergeBuilder()
.WithAssets(b => b.AddItems(pdfFiles))
.SetPdfOutputOptions(o => o.SetPdfFormat(PdfFormat.A2b));
await using var merged = await sharpClient.MergePdfsAsync(mergeBuilder);
await using var file = File.Create("merged.pdf");
await merged.CopyToAsync(file);
// ── Merge from multiple URL conversions (parallel) ───────────────────────────
var sites = new[] { "https://example.com", "https://example.org" }
.Select(u => new Uri(u));
var pdfTasks = sites.Select(uri =>
sharpClient.UrlToPdfAsync(
new UrlRequestBuilder()
.SetUrl(uri)
.ConfigureRequest(r => r.SetPageRanges("1-2"))
.WithPageProperties(pp => pp.UseChromeDefaults().SetLandscape())));
var pdfs = await Task.WhenAll(pdfTasks);
var multiMerge = new MergeBuilder()
.WithAssets(b => b.AddItems(
pdfs.Select((s, i) => KeyValuePair.Create($"{i}.pdf", s))));
await using var final = await sharpClient.MergePdfsAsync(multiMerge);
```
--------------------------------
### Generate PDF from HTML using HtmlRequestBuilder
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/index.md
Create an HTML-to-PDF request using the HtmlRequestBuilder. This example demonstrates setting HTML body content and applying default Chrome page properties. The generated PDF is then obtained asynchronously.
```csharp
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody("
Hello PDF!
"))
.WithPageProperties(pp => pp.UseChromeDefaults());
var result = await sharpClient.HtmlToPdfAsync(builder);
```
--------------------------------
### Manual Client Instantiation
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Demonstrates how to manually instantiate the GotenbergSharpClient using an HttpClient, suitable for console applications or unit tests. It includes configuration for service URL, timeout, and basic authentication.
```APIDOC
## Manual (Non-DI) Client Instantiation
Construct `GotenbergSharpClient` directly from an `HttpClient` for console apps or unit tests.
```csharp
using Gotenberg.Sharp.API.Client;
using Gotenberg.Sharp.API.Client.Domain.Settings;
using Gotenberg.Sharp.API.Client.Infrastructure.Pipeline;
var options = new GotenbergSharpClientOptions
{
ServiceUrl = new Uri("http://localhost:3000"),
TimeOut = TimeSpan.FromMinutes(5),
BasicAuthUsername = "testuser",
BasicAuthPassword = "testpass"
};
HttpMessageHandler handler = new HttpClientHandler();
if (!string.IsNullOrWhiteSpace(options.BasicAuthUsername))
{
handler = new BasicAuthHandler(options.BasicAuthUsername!, options.BasicAuthPassword!)
{ InnerHandler = new HttpClientHandler() };
}
using var httpClient = new HttpClient(handler)
{
BaseAddress = options.ServiceUrl,
Timeout = options.TimeOut
};
var sharpClient = new GotenbergSharpClient(httpClient);
// Verify server version
string? version = await sharpClient.GetVersion();
Console.WriteLine($"Gotenberg version: {version}");
```
```
--------------------------------
### Register GotenbergSharpClient with Dependency Injection
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Demonstrates how to register the GotenbergSharpClient using `AddGotenbergSharpClient` with different configuration approaches: from appsettings.json, programmatically, or a hybrid method with environment variable overrides.
```csharp
// appsettings.json
{
"GotenbergSharpClient": {
"ServiceUrl": "http://localhost:3000",
"HealthCheckUrl": "http://localhost:3000/health",
"BasicAuthUsername": "testuser", // optional
"BasicAuthPassword": "testpass", // optional
"RetryPolicy": {
"Enabled": true,
"RetryCount": 4,
"BackoffPower": 1.5,
"LoggingEnabled": true
}
}
}
// Program.cs / Startup.cs
using Gotenberg.Sharp.API.Client;
using Gotenberg.Sharp.API.Client.Domain.Settings;
using Gotenberg.Sharp.API.Client.Extensions;
// Bind from config
services.AddOptions()
.Bind(Configuration.GetSection("GotenbergSharpClient"));
services.AddGotenbergSharpClient();
// --- OR: fully programmatic ---
services.AddOptions()
.Configure(options =>
{
options.ServiceUrl = new Uri("http://localhost:3000");
options.TimeOut = TimeSpan.FromMinutes(5);
options.BasicAuthUsername = "testuser";
options.BasicAuthPassword = "testpass";
options.RetryPolicy = new RetryOptions
{
Enabled = true,
RetryCount = 4,
BackoffPower = 1.5,
LoggingEnabled = true
};
});
services.AddGotenbergSharpClient();
// --- OR: hybrid (config + env-var overrides) ---
services.AddOptions()
.Bind(Configuration.GetSection("GotenbergSharpClient"))
.PostConfigure(options =>
{
options.BasicAuthUsername = Environment.GetEnvironmentVariable("GOTENBERG_USER");
options.BasicAuthPassword = Environment.GetEnvironmentVariable("GOTENBERG_PASS");
});
services.AddGotenbergSharpClient();
// Inject and use
public class MyService(GotenbergSharpClient sharpClient)
{
public async Task GetPdf()
{
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody("Hello PDF!
"))
.WithPageProperties(pp => pp.UseChromeDefaults());
return await sharpClient.HtmlToPdfAsync(builder);
}
}
```
--------------------------------
### Configure Client with Basic Auth in appsettings.json
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Sets up basic authentication credentials for the Gotenberg Sharp Client within the appsettings.json configuration.
```json
{
"GotenbergSharpClient": {
"ServiceUrl": "http://localhost:3000",
"BasicAuthUsername": "your-username",
"BasicAuthPassword": "your-password"
}
}
```
--------------------------------
### Configure Services in C#
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Registers the Gotenberg Sharp Client with dependency injection in a .NET application, binding options from configuration.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions()
.Bind(Configuration.GetSection("GotenbergSharpClient"));
services.AddGotenbergSharpClient();
}
```
--------------------------------
### Build and Test Locally
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/RELEASES.MD
Execute these commands to build the project and run tests locally on the release branch.
```bash
dotnet build
dotnet test
```
--------------------------------
### Create PDF from HTML
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Demonstrates how to create a PDF document from an HTML string using the GotenbergSharpClient and HtmlRequestBuilder.
```csharp
public async Task CreatePdf([FromServices] GotenbergSharpClient sharpClient)
{
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody("Hello PDF!
"))
.WithPageProperties(pp => pp.UseChromeDefaults());
return await sharpClient.HtmlToPdfAsync(builder);
}
```
--------------------------------
### Configure GotenbergSharpClient with Dependency Injection
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/index.md
Configure the GotenbergSharpClient options and register it with the dependency injection container. Ensure your configuration is bound from a relevant section, typically named 'GotenbergSharpClient'.
```csharp
services.AddOptions()
.Bind(Configuration.GetSection("GotenbergSharpClient"));
services.AddGotenbergSharpClient();
```
--------------------------------
### Hybrid Client Configuration
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Combines configuration from appsettings.json with environment variable overrides for basic authentication credentials.
```csharp
services.AddOptions()
.Bind(Configuration.GetSection("GotenbergSharpClient"))
.PostConfigure(options =>
{
options.BasicAuthUsername = Environment.GetEnvironmentVariable("GOTENBERG_USER");
options.BasicAuthPassword = Environment.GetEnvironmentVariable("GOTENBERG_PASS");
});
services.AddGotenbergSharpClient();
```
--------------------------------
### Screenshot with Conversion Behaviors
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/screenshots.md
Illustrates how to apply conversion behaviors, such as waiting for specific selectors or emulating media features, to screenshot generation.
```APIDOC
## Screenshot with Conversion Behaviors
### Description
Apply advanced Chromium rendering behaviors to your screenshots, similar to PDF conversions.
### Method
```csharp
var builder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(html))
.WithScreenshotProperties(p => p
.SetSize(1920, 1080)
.SetFormat(ScreenshotFormat.Png))
.SetConversionBehaviors(b => b
.SetWaitForSelector("#loaded")
.AddEmulatedMediaFeature("prefers-color-scheme", "dark")
.SkipNetworkIdleEvent());
```
```
--------------------------------
### Configure Gotenberg Sharp API Client with Dependency Injection
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/README.md
Configure the client options and register the GotenbergSharpClient with the service collection in your ASP.NET Core application's Startup.cs.
```csharp
// Startup.cs
services.AddOptions()
.Bind(Configuration.GetSection("GotenbergSharpClient"));
services.AddGotenbergSharpClient();
```
--------------------------------
### Configure Client with appsettings.json
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Configures the Gotenberg Sharp Client using settings from appsettings.json, including service URLs and retry policy.
```json
{
"GotenbergSharpClient": {
"ServiceUrl": "http://localhost:3000",
"HealthCheckUrl": "http://localhost:3000/health",
"RetryPolicy": {
"Enabled": true,
"RetryCount": 4,
"BackoffPower": 1.5,
"LoggingEnabled": true
}
}
}
```
--------------------------------
### Screenshot from HTML
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/screenshots.md
Demonstrates how to create a screenshot from provided HTML content. You can customize the body, size, and format of the output image.
```APIDOC
## Screenshot from HTML
### Description
Capture a screenshot from raw HTML content.
### Method
```csharp
var builder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(@"
Screenshot Demo
"))
.WithScreenshotProperties(p => p
.SetSize(1280, 720)
.SetFormat(ScreenshotFormat.Png));
var imageStream = await sharpClient.ScreenshotHtmlAsync(builder);
```
```
--------------------------------
### Apply Cross-Cutting Output Options
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Configure watermarks, stamps, page rotation, splitting, and PDF encryption using options available on all request builder types. Ensure to import RotationAngle and other necessary value objects.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.ValueObjects; // RotationAngle
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(html))
// Background text watermark (behind content)
.SetWatermarkOptions(w => w
.SetTextWatermark("CONFIDENTIAL") // all pages
// .SetTextWatermark("DRAFT", "1-3") // specific pages only
)
// Foreground text stamp (on top of content)
.SetStampOptions(s => s.SetTextStamp("APPROVED", "1"))
// Rotate pages during conversion
.SetRotationOptions(r => r
.SetAngle(RotationAngle.Degrees90)
.SetPages("2-3")) // optional page range
// Split the output
.SetSplitOptions(s => s.SplitByPages("1-3,5", unify: true))
// PDF output format + encryption
.SetPdfOutputOptions(o => o
.SetPdfFormat(PdfFormat.A2b)
.SetPdfUa()
.SetGenerateTaggedPdf()
.SetFlatten()
.SetEncryption(userPassword: "reader", ownerPassword: "admin"))
.WithPageProperties(pp => pp.UseChromeDefaults());
await using var result = await sharpClient.HtmlToPdfAsync(builder);
```
--------------------------------
### Instantiate GotenbergSharpClient Manually
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Instantiate the client directly from an HttpClient. Useful for console applications or unit tests where dependency injection is not used. Ensure the HttpClient is configured with the correct service URL, timeout, and authentication if required.
```csharp
using Gotenberg.Sharp.API.Client;
using Gotenberg.Sharp.API.Client.Domain.Settings;
using Gotenberg.Sharp.API.Client.Infrastructure.Pipeline;
var options = new GotenbergSharpClientOptions
{
ServiceUrl = new Uri("http://localhost:3000"),
TimeOut = TimeSpan.FromMinutes(5),
BasicAuthUsername = "testuser",
BasicAuthPassword = "testpass"
};
HttpMessageHandler handler = new HttpClientHandler();
if (!string.IsNullOrWhiteSpace(options.BasicAuthUsername))
{
handler = new BasicAuthHandler(options.BasicAuthUsername!, options.BasicAuthPassword!)
{ InnerHandler = new HttpClientHandler() };
}
using var httpClient = new HttpClient(handler)
{
BaseAddress = options.ServiceUrl,
Timeout = options.TimeOut
};
var sharpClient = new GotenbergSharpClient(httpClient);
// Verify server version
string? version = await sharpClient.GetVersion();
Console.WriteLine($"Gotenberg version: {version}");
```
--------------------------------
### Split Output During Conversion
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/pdf-manipulation.md
Configure splitting of the output during conversion using SetSplitOptions(). Pages can be specified by range, and the output can be unified.
```csharp
builder.SetSplitOptions(s => s.SplitByPages("1-3,5", unify: true));
```
--------------------------------
### Screenshot with Conversion Behaviors
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/screenshots.md
Configure advanced screenshot capture by applying conversion behaviors, such as waiting for a specific selector, emulating media features, or skipping network idle events.
```csharp
var builder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(html))
.WithScreenshotProperties(p => p
.SetSize(1920, 1080)
.SetFormat(ScreenshotFormat.Png))
.SetConversionBehaviors(b => b
.SetWaitForSelector("#loaded")
.AddEmulatedMediaFeature("prefers-color-scheme", "dark")
.SkipNetworkIdleEvent());
```
--------------------------------
### Convert PDF to PDF/A or PDF/UA using PdfConversionBuilder
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Use this builder to convert existing PDFs to PDF/A (e.g., A2b) or PDF/UA formats. Optional flattening can be applied. Ensure the input PDF files are available.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.PdfFormat;
var builder = new PdfConversionBuilder()
.WithPdfs(b => b.AddItem("document.pdf", File.ReadAllBytes("document.pdf")))
.SetPdfOutputOptions(o => o
.SetPdfFormat(PdfFormat.A2b) // A1b | A2b | A3b
.SetPdfUa()
.SetFlatten());
await using var converted = await sharpClient.ConvertPdfDocumentsAsync(builder);
await using var file = File.Create("converted-pdfa.pdf");
await converted.CopyToAsync(file);
```
--------------------------------
### Configure Page Properties with Presets
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Use preset paper sizes and margins for page configuration. Supports landscape orientation and background printing.
```csharp
using Gotenberg.Sharp.API.Client.Domain.Pages;
using Gotenberg.Sharp.API.Client.Domain.Dimensions;
builder.WithPageProperties(pp =>
{
// Preset paper sizes: A3, A4, Letter, Legal, Tabloid, ...
pp.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.Normal) // Normal | None | Large
.SetScale(0.95)
.SetLandscape()
.SetPrintBackground(true)
.SetGenerateDocumentOutline(true)
.SetSinglePage(false); // force all content on one tall page
});
// Custom paper dimensions
builder.WithPageProperties(pp =>
pp.SetPaperWidth(Dimension.FromInches(8.5))
.SetPaperHeight(Dimension.FromInches(14))
.SetMarginTop(Dimension.FromCentimeters(1.5))
.SetMarginBottom(Dimension.FromCentimeters(1.5)));
```
--------------------------------
### Screenshot from URL
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/screenshots.md
Shows how to capture a screenshot of a given URL. Options include setting the URL, image size, format, quality, and clipping.
```APIDOC
## Screenshot from URL
### Description
Capture a screenshot from a web URL.
### Method
```csharp
var builder = new ScreenshotUrlRequestBuilder()
.SetUrl("https://example.com")
.WithScreenshotProperties(p => p
.SetSize(1024, 768)
.SetFormat(ScreenshotFormat.Jpeg)
.SetQuality(90)
.SetClip());
var imageStream = await sharpClient.ScreenshotUrlAsync(builder);
```
```
--------------------------------
### Fine-tune Office to PDF Conversion with LibreOffice Options
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/office-conversion.md
This snippet demonstrates how to apply specific LibreOffice conversion options, such as image compression (quality, resolution) and export settings (bookmarks, form fields, watermarks).
```csharp
var builder = new MergeOfficeBuilder()
.WithAsyncAssets(async a => a.AddItems(await GetDocsAsync(sourceDirectory)))
.SetLibreOfficeOptions(o => o
// Image compression
.SetQuality(85) // JPEG quality 1-100
.SetReduceImageResolution()
.SetMaxImageResolution(300) // DPI: 75, 150, 300, 600, 1200
// Export options
.SetExportBookmarks()
.SetExportFormFields(false) // Flatten form fields
.SetUpdateIndexes()
// Native watermark
.SetNativeWatermarkText("DRAFT")
.SetNativeWatermarkFontName("Arial")
.SetNativeWatermarkFontHeight(48))
.SetPdfOutputOptions(o => o.SetPdfFormat(PdfFormat.A2b));
```
--------------------------------
### Convert Office Documents to PDF using Gotenberg Sharp API Client
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/README.md
Employ the MergeOfficeBuilder to specify office documents, LibreOffice options, and PDF output settings for conversion to PDF.
```csharp
var builder = new MergeOfficeBuilder()
.WithAsyncAssets(async a => a.AddItems(await GetDocsAsync(sourceDir)))
.SetLibreOfficeOptions(o => o.SetQuality(85).SetExportBookmarks())
.SetPdfOutputOptions(o => o.SetPdfFormat(PdfFormat.A2b));
var result = await sharpClient.MergeOfficeDocsAsync(builder);
```
--------------------------------
### Programmatic Client Configuration
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Configures the Gotenberg Sharp Client programmatically, setting service URLs, timeouts, basic auth, and retry options.
```csharp
services.AddOptions()
.Configure(options =>
{
options.ServiceUrl = new Uri("http://localhost:3000");
options.TimeOut = TimeSpan.FromMinutes(5);
options.BasicAuthUsername = "username";
options.BasicAuthPassword = "password";
options.RetryPolicy = new RetryOptions
{
Enabled = true,
RetryCount = 4,
BackoffPower = 1.5,
LoggingEnabled = true
};
});
services.AddGotenbergSharpClient();
```
--------------------------------
### Configure Chromium Rendering Behaviors: Wait for Selector, Media Features, and Error Handling
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Customize Chromium rendering by setting wait conditions, emulating media features like dark mode, and configuring strict error handling for HTTP status codes and resource loading.
```csharp
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(html))
.SetConversionBehaviors(b => b
// Wait for a DOM element before converting
.SetWaitForSelector("#app")
// Emulate dark mode
.AddEmulatedMediaFeature("prefers-color-scheme", "dark")
// Strict error handling
.SetFailOnHttpStatusCodes(499, 599)
.FailOnResourceLoadingFailed()
.FailOnConsoleExceptions()
// Ignore specific CDN domains for status checks
.AddIgnoreResourceHttpStatusDomains("cdn.example.com", "fonts.googleapis.com"));
```
--------------------------------
### Configure Chromium Rendering Behaviors
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Use SetConversionBehaviors to control DOM wait conditions, emulate media features, inject cookies, set custom HTTP headers, and configure strict error handling for PDF conversion and screenshots.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.Cookies;
var builder = new HtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(html))
.SetConversionBehaviors(b => b
// Wait for a DOM element before snapshotting
.SetWaitForSelector("#app-loaded")
// Emulate media features (dark mode, forced-colors, etc.)
.AddEmulatedMediaFeature("prefers-color-scheme", "dark")
.AddEmulatedMediaFeature("forced-colors", "active")
// Strict HTTP status code failures (e.g., 4xx or 5xx)
.SetFailOnHttpStatusCodes(499, 599)
.FailOnResourceLoadingFailed()
.FailOnConsoleExceptions()
// Ignore CDN domains from status checks
.AddIgnoreResourceHttpStatusDomains("cdn.example.com", "fonts.googleapis.com")
// Skip waiting for network idle (speeds up JS-heavy pages)
.SkipNetworkIdleEvent()
// Inject session cookies
.AddCookie(new Cookie
{
Name = "session_token",
Value = "abc123xyz",
Domain = "example.com",
Path = "/",
Secure = true,
HttpOnly = true,
SameSite = "Lax"
})
// Additional HTTP request headers sent by Chromium
.AddAdditionalHeaders("Authorization", "Bearer my-token")
.AddAdditionalHeaders("X-Tenant-Id", "acme-corp"));
```
--------------------------------
### Configure Request Settings - C#
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/advanced-features.md
Apply common request settings across different builders using the ConfigureRequest method. This includes setting trace IDs, page ranges, and output filenames.
```csharp
builder.ConfigureRequest(config =>
{
config.SetTrace("my-request-id") // Custom trace ID for logs
.SetPageRanges("1-5") // Page range selection
.SetResultFileName("output.pdf"); // Output filename
});
```
--------------------------------
### Configure Paper Sizes, Margins, and Orientation
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Set page properties including paper size (e.g., A4, Letter), margins (e.g., Normal, None), scale, and orientation (landscape or portrait). Background printing and document outline generation can also be enabled.
```csharp
builder.WithPageProperties(pp =>
{
pp.SetPaperSize(PaperSizes.A4) // or Letter, A3, etc.
.SetMargins(Margins.Normal) // or None, Large
.SetScale(0.95)
.SetLandscape()
.SetPrintBackground(true)
.SetGenerateDocumentOutline(true);
});
```
--------------------------------
### Configure Custom Paper Dimensions and Margins
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Set custom paper width and height using Dimension objects, and define margins using string representations (e.g., '1in 0.5in').
```csharp
builder.WithPageProperties(pp =>
{
pp.SetPaperWidth(Dimension.FromInches(8.5))
.SetPaperHeight(Dimension.FromInches(14))
.SetMargins("1in 0.5in"); // top/bottom, left/right
});
```
--------------------------------
### Capture HTML Screenshot with GotenbergSharp
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Generates a PNG screenshot from provided HTML content. Configures screenshot properties like size, format, and background, and includes conversion behaviors such as waiting for a specific selector and emulating media features.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.ValueObjects; // ScreenshotFormat
// ── HTML screenshot ─────────────────────────────────────────────────────────
var htmlBuilder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody(@"
Screenshot Demo
"))
.WithScreenshotProperties(p => p
.SetSize(1280, 720)
.SetFormat(ScreenshotFormat.Png)
.SetOmitBackground()) // transparent background
.SetConversionBehaviors(b => b
.SetWaitForSelector("#loaded")
.AddEmulatedMediaFeature("prefers-color-scheme", "dark"));
await using var png = await sharpClient.ScreenshotHtmlAsync(htmlBuilder);
await using var pngFile = File.Create("screenshot.png");
await png.CopyToAsync(pngFile);
```
--------------------------------
### Create Release Branch
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/RELEASES.MD
Use this command to create a new release branch from the develop branch.
```bash
git checkout develop
git pull origin develop
git checkout -b release/X.Y.Z
```
--------------------------------
### Convert PDF to PDF/A with Transformations
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/pdf-manipulation.md
Use PdfConversionBuilder to convert PDFs to a specific PDF/A format (e.g., A2b) and apply transformations like flattening. Requires specifying input PDFs and output options.
```csharp
var builder = new PdfConversionBuilder()
.WithPdfs(b => b.AddItem("document.pdf", File.ReadAllBytes(pdfPath)))
.SetPdfOutputOptions(o => o
.SetPdfFormat(PdfFormat.A2b)
.SetPdfUa()
.SetFlatten());
var result = await sharpClient.ConvertPdfDocumentsAsync(builder);
```
--------------------------------
### Required Using Statements
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/getting-started.md
Lists the necessary using statements for utilizing the Gotenberg Sharp API Client and its related components.
```csharp
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;
using Gotenberg.Sharp.API.Client.Domain.ValueObjects;
```
--------------------------------
### Configure Single Page Output
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Force all content to render onto a single, potentially very long, page by setting the single page option within page properties.
```csharp
builder.WithPageProperties(pp => pp.UseChromeDefaults().SetSinglePage(true));
```
--------------------------------
### Take a Screenshot of HTML using Gotenberg Sharp API Client
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/README.md
Utilize the ScreenshotHtmlRequestBuilder to specify HTML content and screenshot properties, then capture the output as an image stream.
```csharp
var builder = new ScreenshotHtmlRequestBuilder()
.AddDocument(doc => doc.SetBody("Screenshot!
"))
.WithScreenshotProperties(p => p.SetSize(1280, 720).SetFormat(ScreenshotFormat.Png));
var imageStream = await sharpClient.ScreenshotHtmlAsync(builder);
```
--------------------------------
### Process Conversions Asynchronously with Webhooks
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Utilize FireWebhookAndForgetAsync to submit conversion jobs asynchronously. The generated PDF is POSTed to a configured webhook URL upon completion. This method returns immediately after the job is queued.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.Pages;
var builder = new UrlRequestBuilder()
.SetUrl("https://www.example.com")
.ConfigureRequest(req =>
{
req.AddWebhook(hook =>
{
hook.SetUrl("http://host.docker.internal:5000/api/webhook/pdf")
.SetErrorUrl("http://host.docker.internal:5000/api/webhook/error")
.AddExtraHeader("X-Request-Id", Guid.NewGuid().ToString());
});
req.SetPageRanges("1-2")
.SetTrace("webhook-demo");
})
.WithPageProperties(pp =>
pp.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None));
// Returns as soon as Gotenberg accepts the job (~milliseconds)
await sharpClient.FireWebhookAndForgetAsync(builder);
Console.WriteLine("Job queued; PDF will be POSTed to webhook URL.");
```
--------------------------------
### Convert Markdown to PDF with Headers, Footers, and Assets
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Convert Markdown content to PDF using HtmlRequestBuilder. Supports asynchronous setting of headers, footers, body content, and assets, along with page properties and markdown conversion.
```csharp
var builder = new HtmlRequestBuilder()
.AddAsyncDocument(async doc =>
doc.SetHeader(await GetHeaderAsync())
.SetBody(await GetBodyAsync())
.SetContainsMarkdown()
.SetFooter(await GetFooterAsync()))
.WithPageProperties(pp =>
pp.UseChromeDefaults().SetLandscape().SetScale(.90))
.WithAsyncAssets(async a =>
a.AddItems(await GetMarkdownAssets()));
var result = await sharpClient.HtmlToPdfAsync(builder);
```
--------------------------------
### HtmlToPdfAsync
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Converts HTML or Markdown content to PDF using Chromium. This method accepts a builder pattern for configuring the HTML document, optional headers/footers, embedded assets, page properties, and request configurations. It returns a PDF as a Stream.
```APIDOC
## `HtmlToPdfAsync` — HTML / Markdown to PDF
Converts an HTML document (body, optional header/footer, embedded assets) to PDF using Chromium. Accepts a builder or a pre-built `HtmlRequest`. Returns a `Stream`.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.Pages;
// ── Basic HTML with inline assets ──────────────────────────────────────────
var builder = new HtmlRequestBuilder()
.AddAsyncDocument(async doc =>
doc.SetBody(await File.ReadAllBytesAsync("body.html"))
.SetFooter(await File.ReadAllBytesAsync("footer.html")))
.WithPageProperties(pp =>
pp.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None)
.SetScale(0.95)
.SetLandscape()
.SetPrintBackground(true))
.WithAsyncAssets(async a =>
a.AddItem("logo.jpg", await File.ReadAllBytesAsync("logo.jpg")))
.ConfigureRequest(c => c.SetPageRanges("1").SetTrace("my-request-id"));
await using var pdfStream = await sharpClient.HtmlToPdfAsync(builder);
await using var file = File.Create("output.pdf");
await pdfStream.CopyToAsync(file);
// ── Markdown with index.html wrapper ────────────────────────────────────────
var mdBuilder = new HtmlRequestBuilder()
.AddAsyncDocument(async doc =>
doc.SetBody(await File.ReadAllBytesAsync("index.html")) // wraps .md files
.SetContainsMarkdown()
.SetHeader(await File.ReadAllBytesAsync("header.html")))
.WithPageProperties(pp => pp.UseChromeDefaults().SetLandscape().SetScale(.90))
.WithAsyncAssets(async a =>
{
a.AddItem("paragraph1.md", await File.ReadAllBytesAsync("paragraph1.md"));
a.AddItem("paragraph2.md", await File.ReadAllBytesAsync("paragraph2.md"));
a.AddItem("style.css", await File.ReadAllBytesAsync("style.css"));
});
await using var mdPdf = await sharpClient.HtmlToPdfAsync(mdBuilder);
```
```
--------------------------------
### Capture URL Screenshot with GotenbergSharp
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Generates a JPEG screenshot from a given URL. Allows configuration of screenshot properties like size, format, quality, and clipping, suitable for capturing web page snapshots.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.ValueObjects; // ScreenshotFormat
// ── URL screenshot ───────────────────────────────────────────────────────────
var urlBuilder = new ScreenshotUrlRequestBuilder()
.SetUrl("https://example.com")
.WithScreenshotProperties(p => p
.SetSize(1024, 768)
.SetFormat(ScreenshotFormat.Jpeg)
.SetQuality(90)
.SetClip());
await using var jpeg = await sharpClient.ScreenshotUrlAsync(urlBuilder);
await using var jpegFile = File.Create("screenshot.jpg");
await jpeg.CopyToAsync(jpegFile);
```
--------------------------------
### Execute Standalone PDF Engine Operations with PdfEngineBuilders
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Utilize PdfEngineBuilders for direct PDF manipulations. This includes flattening form fields, rotating pages by specific degrees or page ranges, splitting PDFs by interval or page numbers, extracting and unifying pages, encrypting with passwords, and writing XMP metadata. Input PDF files must be accessible.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.Split;
var pdfBytes = await File.ReadAllBytesAsync("input.pdf");
// Flatten form fields
await using var flat = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Flatten()
.WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
await using var f1 = File.Create("flattened.pdf");
await flat.CopyToAsync(f1);
```
```csharp
// Rotate all pages 90 degrees
await using var rotated = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Rotate(90)
.WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
```
```csharp
// Rotate pages 1-3 by 180 degrees
await using var rotated2 = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Rotate(180, "1-3")
.WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
```
```csharp
// Split every 2 pages (returns ZIP archive)
await using var split = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Split(SplitMode.Intervals, "2")
.WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
```
```csharp
// Extract and unify pages 1-3 and 5 into one PDF
await using var extracted = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Split(SplitMode.Pages, "1-3,5", unify: true)
.WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
```
```csharp
// Encrypt with user and owner passwords
await using var encrypted = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Encrypt("reader123", "admin456")
.WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
```
```csharp
// Write XMP metadata
await using var withMeta = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.WriteMetadata(new Dictionary
{
{ "Author", "Jane Doe" },
{ "Title", "Annual Report 2025" }
}).WithPdfs(a => a.AddItem("input.pdf", pdfBytes)));
```
--------------------------------
### Send PDF to Webhook - C#
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/advanced-features.md
Configure a request to generate a PDF and send it to a webhook URL upon completion. Supports setting webhook URLs, error URLs, and custom headers.
```csharp
var builder = new UrlRequestBuilder()
.SetUrl("https://www.example.com")
.ConfigureRequest(req =>
{
req.AddWebhook(hook =>
{
hook.SetUrl("http://host.docker.internal:5000/api/webhook/pdf")
.SetErrorUrl("http://host.docker.internal:5000/api/webhook/error")
.AddExtraHeader("custom-header", "value");
});
req.SetPageRanges("1-2");
})
.WithPageProperties(pp => pp.SetPaperSize(PaperSizes.A4));
await sharpClient.FireWebhookAndForgetAsync(builder);
```
--------------------------------
### Screenshot URL Request Builder
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/screenshots.md
Use this builder to create a request for capturing a screenshot of a given URL. Configure URL, screenshot dimensions, format, quality, and clipping.
```csharp
var builder = new ScreenshotUrlRequestBuilder()
.SetUrl("https://example.com")
.WithScreenshotProperties(p => p
.SetSize(1024, 768)
.SetFormat(ScreenshotFormat.Jpeg)
.SetQuality(90)
.SetClip());
var imageStream = await sharpClient.ScreenshotUrlAsync(builder);
```
--------------------------------
### Basic Office Document Merge to PDF
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/office-conversion.md
Use this snippet to perform a basic merge of office documents into a PDF. It allows setting PDF output options like the PDF format.
```csharp
var builder = new MergeOfficeBuilder()
.WithAsyncAssets(async a => a.AddItems(await GetDocsAsync(sourceDirectory)))
.SetPdfOutputOptions(o => o.SetPdfFormat(PdfFormat.A2b));
var result = await sharpClient.MergeOfficeDocsAsync(builder);
```
--------------------------------
### Set Split Options
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/pdf-manipulation.md
Set split options for the output during conversion.
```APIDOC
## Set Split Options
### Description
Split output during conversion.
### Method
SetSplitOptions (on a Request Builder)
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None (uses builder pattern)
### Request Example
```csharp
builder.SetSplitOptions(s => s.SplitByPages("1-3,5", unify: true));
```
### Response
N/A (part of a larger request builder)
```
--------------------------------
### Convert HTML to PDF with Assets, Headers, and Footers
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Use HtmlRequestBuilder to convert HTML content to PDF. Supports setting body, headers, footers, page properties, and asynchronous assets like images.
```csharp
var builder = new HtmlRequestBuilder()
.AddDocument(doc =>
doc.SetBody(GetBody()).SetFooter(GetFooter()))
.WithPageProperties(pp =>
{
pp.SetPaperSize(PaperSizes.A3)
.SetMargins(Margins.None)
.SetScale(.99);
})
.WithAsyncAssets(async assets =>
assets.AddItem("some-image.jpg", await GetImageBytes()));
var result = await sharpClient.HtmlToPdfAsync(builder);
```
--------------------------------
### Asynchronous Webhook Processing
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Submits a conversion request to Gotenberg asynchronously. The method returns immediately, and Gotenberg POSTs the generated PDF to the configured webhook URL.
```APIDOC
## `FireWebhookAndForgetAsync` — Asynchronous Webhook Processing
Submits a conversion request to Gotenberg asynchronously. Returns immediately; Gotenberg POSTs the generated PDF to the configured webhook URL.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.Pages;
var builder = new UrlRequestBuilder()
.SetUrl("https://www.example.com")
.ConfigureRequest(req =>
{
req.AddWebhook(hook =>
{
hook.SetUrl("http://host.docker.internal:5000/api/webhook/pdf")
.SetErrorUrl("http://host.docker.internal:5000/api/webhook/error")
.AddExtraHeader("X-Request-Id", Guid.NewGuid().ToString());
});
req.SetPageRanges("1-2")
.SetTrace("webhook-demo");
})
.WithPageProperties(pp =>
pp.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None));
// Returns as soon as Gotenberg accepts the job (~milliseconds)
await sharpClient.FireWebhookAndForgetAsync(builder);
Console.WriteLine("Job queued; PDF will be POSTed to webhook URL.");
```
```
--------------------------------
### Perform PDF Operations (Rotate, Encrypt) with Gotenberg Sharp API Client
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/README.md
Execute PDF engine operations like rotating or encrypting documents using the PdfEngineBuilders. Requires providing the PDF content as bytes.
```csharp
// Rotate
using var rotated = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Rotate(90).WithPdfs(a => a.AddItem("doc.pdf", bytes)));
// Encrypt
using var encrypted = await sharpClient.ExecutePdfEngineAsync(
PdfEngineBuilders.Encrypt("reader123", "admin456").WithPdfs(a => a.AddItem("doc.pdf", bytes)));
```
--------------------------------
### Convert HTML/Markdown to PDF
Source: https://context7.com/changemakerstudios/gotenbergsharpapiclient/llms.txt
Converts HTML or Markdown content to PDF using Chromium. Supports inline assets, page properties, headers/footers, and custom request configurations. The output is returned as a Stream.
```csharp
using Gotenberg.Sharp.API.Client.Application.Builders;
using Gotenberg.Sharp.API.Client.Domain.Pages;
// ── Basic HTML with inline assets ──────────────────────────────────────────
var builder = new HtmlRequestBuilder()
.AddAsyncDocument(async doc =>
doc.SetBody(await File.ReadAllBytesAsync("body.html"))
.SetFooter(await File.ReadAllBytesAsync("footer.html")))
.WithPageProperties(pp =>
pp.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None)
.SetScale(0.95)
.SetLandscape()
.SetPrintBackground(true))
.WithAsyncAssets(async a =>
a.AddItem("logo.jpg", await File.ReadAllBytesAsync("logo.jpg")))
.ConfigureRequest(c => c.SetPageRanges("1").SetTrace("my-request-id"));
await using var pdfStream = await sharpClient.HtmlToPdfAsync(builder);
await using var file = File.Create("output.pdf");
await pdfStream.CopyToAsync(file);
// ── Markdown with index.html wrapper ────────────────────────────────────────
var mdBuilder = new HtmlRequestBuilder()
.AddAsyncDocument(async doc =>
doc.SetBody(await File.ReadAllBytesAsync("index.html")) // wraps .md files
.SetContainsMarkdown()
.SetHeader(await File.ReadAllBytesAsync("header.html")))
.WithPageProperties(pp => pp.UseChromeDefaults().SetLandscape().SetScale(.90))
.WithAsyncAssets(async a =>
{
a.AddItem("paragraph1.md", await File.ReadAllBytesAsync("paragraph1.md"));
a.AddItem("paragraph2.md", await File.ReadAllBytesAsync("paragraph2.md"));
a.AddItem("style.css", await File.ReadAllBytesAsync("style.css"));
});
await using var mdPdf = await sharpClient.HtmlToPdfAsync(mdBuilder);
```
--------------------------------
### Set Password for Source Office Document
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/office-conversion.md
This snippet shows how to specify a password for an encrypted source office document when performing a conversion.
```csharp
builder.SetLibreOfficeOptions(o => o.SetPassword("document-password"));
```
--------------------------------
### Convert URL to PDF with Custom Page Ranges, Headers, and Footers
Source: https://github.com/changemakerstudios/gotenbergsharpapiclient/blob/develop/docs/html-and-url-to-pdf.md
Use UrlRequestBuilder to convert a URL to PDF. Allows configuration of request settings, asynchronous headers/footers, and page properties like paper size, margins, and orientation.
```csharp
var builder = new UrlRequestBuilder()
.SetUrl("https://www.example.com")
.ConfigureRequest(config => config.SetPageRanges("1-2"))
.AddAsyncHeaderFooter(async doc =>
doc.SetHeader(await File.ReadAllTextAsync(headerPath))
.SetFooter(await File.ReadAllBytesAsync(footerPath)))
.WithPageProperties(pp =>
{
pp.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None)
.SetScale(.90)
.SetLandscape();
});
var result = await sharpClient.UrlToPdfAsync(builder);
```