Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ChangemakerStudios/GotenbergSharpApiClient
.NET C# Client for the Gotenberg API
https://github.com/ChangemakerStudios/GotenbergSharpApiClient
api-client async csharp fluent gotenberg html-to-pdf httpclientfactory netstandard nuget nuget-package pdf pdf-converter pdf-generation pdf-merge polly-resilience typed-clients url-to-pdf word-to-pdf
Last synced: 29 days ago
JSON representation
.NET C# Client for the Gotenberg API
- Host: GitHub
- URL: https://github.com/ChangemakerStudios/GotenbergSharpApiClient
- Owner: ChangemakerStudios
- License: apache-2.0
- Created: 2019-04-25T20:34:55.000Z (over 5 years ago)
- Default Branch: develop
- Last Pushed: 2024-09-27T13:22:49.000Z (3 months ago)
- Last Synced: 2024-11-05T07:34:33.460Z (about 1 month ago)
- Topics: api-client, async, csharp, fluent, gotenberg, html-to-pdf, httpclientfactory, netstandard, nuget, nuget-package, pdf, pdf-converter, pdf-generation, pdf-merge, polly-resilience, typed-clients, url-to-pdf, word-to-pdf
- Language: Rich Text Format
- Homepage:
- Size: 2.08 MB
- Stars: 122
- Watchers: 10
- Forks: 18
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-gotenberg - C# - ChangemakerStudios/GotenbergSharpApiClient
README
# ![gotenberg icon](https://raw.githubusercontent.com/ChangemakerStudios/GotenbergSharpApiClient/develop/lib/Resources/gotenbergSharpClient.PNG) Gotenberg.Sharp.Api.Client
[![NuGet version](https://badge.fury.io/nu/Gotenberg.Sharp.Api.Client.svg)](https://badge.fury.io/nu/Gotenberg.Sharp.Api.Client)
[![Downloads](https://img.shields.io/nuget/dt/Gotenberg.Sharp.API.Client.svg?logo=nuget&color=purple)](https://www.nuget.org/packages/Gotenberg.Sharp.API.Client)
![Build status](https://github.com/ChangemakerStudios/GotenbergSharpApiClient/actions/workflows/deploy.yml/badge.svg)⭐ For Gotenberg v7 & v8 ⭐
.NET C# Client for interacting with the [Gotenberg](https://gotenberg.dev/) v7 & v8 micro-service's API. [Gotenberg](https://github.com/gotenberg/gotenberg) is a [Docker-powered stateless API](https://hub.docker.com/r/gotenberg/gotenberg/) for converting & merging HTML, Markdown and Office documents to PDF. The client supports a configurable [Polly](http://www.thepollyproject.org/) **retry policy** with exponential backoff for handling transient exceptions.
# Getting Started
*Pull the image from dockerhub.com*
```powershell
> docker pull gotenberg/gotenberg:latest
```
*Create & start a container*
```powershell
docker run --name gotenbee8x --rm -p 3000:3000 gotenberg/gotenberg:latest gotenberg --api-timeout=1800s --log-level=debug
```# .NET Core Project Setup
*Install nuget package into your project*
```powershell
PM> Install-Package Gotenberg.Sharp.Api.Client
```*Note: Use v1.x nugets for Gotenberg v6.*
## AppSettings
```json
"GotenbergSharpClient": {
"ServiceUrl": "http://localhost:3000",
"HealthCheckUrl": "http://localhost:3000/health",
"RetryPolicy": {
"Enabled": true,
"RetryCount": 4,
"BackoffPower": 1.5,
"LoggingEnabled": true
}
}
```## Configure Services In Startup.cs
```csharp
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddOptions()
.Bind(Configuration.GetSection(nameof(GotenbergSharpClient)));
services.AddGotenbergSharpClient();
.....
}```
# Using GotenbergSharpClient
*See the [linqPad folder](linqpad/)* for complete examples.### Html To Pdf
*With embedded assets:*```csharp
[HttpGet]
public async Task HtmlToPdf([FromServices] GotenbergSharpClient sharpClient)
{
var builder = new HtmlRequestBuilder()
.AddDocument(doc =>
doc.SetBody(GetBody()).SetFooter(GetFooter())
).WithDimensions(dims =>
{
dims.SetPaperSize(PaperSizes.A3)
.SetMargins(Margins.None)
.SetScale(.99);
}).WithAsyncAssets(async assets => assets.AddItem("some-image.jpg", await GetImageBytes()));var req = await builder.BuildAsync();
var result = await sharpClient.HtmlToPdfAsync(req);
return this.File(result, "application/pdf", "gotenbergFromHtml.pdf");
}
```### Url To Pdf
*Url to Pdf with custom page range, header & footer:*```csharp
public async Task CreateFromUrl(string headerPath, string footerPath)
{
var builder = new UrlRequestBuilder()
.SetUrl("https://www.cnn.com")
.ConfigureRequest(config =>
{
config.SetPageRanges("1-2");
})
.AddAsyncHeaderFooter(async
doc => doc.SetHeader(await File.ReadAllTextAsync(headerPath))
.SetFooter(await File.ReadAllBytesAsync(footerPath)
)).WithDimensions(dims =>
{
dims.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None)
.SetScale(.90)
.LandScape();
});var request = await builder.BuildAsync();
return await _sharpClient.UrlToPdfAsync(request);
}
```
## Merge Office Docs
*Merges office documents and configures the request time-out:*```csharp
public async Task DoOfficeMerge(string sourceDirectory)
{
var builder = new MergeOfficeBuilder()
.WithAsyncAssets(async a => a.AddItems(await GetDocsAsync(sourceDirectory)));var request = await builder.BuildAsync();
return await _sharpClient.MergeOfficeDocsAsync(request);
}
```
### Markdown to Pdf
*Markdown to Pdf conversion with embedded assets:*```csharp
public async Task CreateFromMarkdown()
{
var builder = new HtmlRequestBuilder()
.AddAsyncDocument(async
doc => doc.SetHeader(await this.GetHeaderAsync())
.SetBody(await GetBodyAsync())
.ContainsMarkdown()
.SetFooter(await GetFooterAsync())
).WithDimensions(dims =>
{
dims.UseChromeDefaults().LandScape().SetScale(.90);
}).WithAsyncAssets(async
a => a.AddItems(await GetMarkdownAssets())
);var request = await builder.BuildAsync();
return await _sharpClient.HtmlToPdfAsync(request);
}
```
### Webhook
*All request types support webhooks*```csharp
public async Task SendUrlToWebhookEndpoint(string headerPath, string footerPath)
{
var builder = new UrlRequestBuilder()
.SetUrl("https://www.cnn.com")
.ConfigureRequest(reqBuilder =>
{
reqBuilder.AddWebhook(hook =>
{
hook.SetUrl("http://host.docker.internal:5000/api/your/webhookReceiver")
.SetErrorUrl("http://host.docker.internal:5000/api/your/webhookReceiver/error")
.AddExtraHeader("custom-header", "value");
})
.SetPageRanges("1-2");
})
.AddAsyncHeaderFooter(async
b => b.SetHeader(await System.IO.File.ReadAllTextAsync(headerPath))
.SetFooter(await System.IO.File.ReadAllBytesAsync(footerPath))
).WithDimensions(dimBuilder =>
{
dimBuilder.SetPaperSize(PaperSizes.A4)
.SetMargins(Margins.None)
.SetScale(.90)
.LandScape();
});var request = await builder.BuildAsync();
await _sharpClient.FireWebhookAndForgetAsync(request);
}```
### Merge 15 Urls to one pdf
*Builds a 30 page pdf by merging the front two pages of 15 news sites. Takes about a minute to complete*```csharp
public async Task CreateWorldNewsSummary()
{
var sites = new[]
{
"https://www.nytimes.com", "https://www.axios.com/", "https://www.csmonitor.com",
"https://www.wsj.com", "https://www.usatoday.com", "https://www.irishtimes.com",
"https://www.lemonde.fr", "https://calgaryherald.com", "https://www.bbc.com/news/uk",
"https://www.thehindu.com", "https://www.theaustralian.com.au",
"https://www.welt.de", "https://www.cankaoxiaoxi.com",
"https://www.novinky.cz", "https://www.elobservador.com.uy"
}
.Select(u => new Uri(u));var builders = CreateBuilders(sites);
var requests = builders.Select(b => b.Build());return await ExecuteRequestsAndMerge(requests);
}IEnumerable CreateBuilders(IEnumerable uris)
{
foreach (var uri in uris)
{
yield return new UrlRequestBuilder()
.SetUrl(uri)
.ConfigureRequest(req => { req.SetPageRanges("1-2"); })
.AddHeaderFooter(docBuilder =>
{
docBuilder.SetHeader(GetHeadFoot(uri.Host.Replace("www.", string.Empty).ToUpper()))
.SetFooter(GetHeadFoot(uri.ToString()));
})
.WithDimensions(dimBuilder =>
{
dimBuilder.UseChromeDefaults()
.SetScale(.90)
.LandScape()
.MarginLeft(.5)
.MarginRight(.5);
});
}static string GetHeadFoot(string heading)
=> " body { font-size: 8rem; } h1 { margin-left: auto; margin-right: auto; }" +
";
heading + "
}async Task ExecuteRequestsAndMerge(IEnumerable requests)
{
var tasks = requests.Select(r => _sharpClient.UrlToPdfAsync(r));
var results = await Task.WhenAll(tasks);var mergeBuilder = new MergeBuilder()
.WithAssets(b => {
b.AddItems(results.Select((r, i) => KeyValuePair.Create($"{i}.pdf", r)));
});var request = mergeBuilder.Build();
return await _sharpClient.MergePdfsAsync(request);
}
```