|
| 1 | +using Gotenberg.Sharp.API.Client; |
| 2 | +using Gotenberg.Sharp.API.Client.Domain.Builders; |
| 3 | +using Gotenberg.Sharp.API.Client.Domain.Builders.Faceted; |
| 4 | +using Gotenberg.Sharp.API.Client.Domain.Requests; |
| 5 | +using Gotenberg.Sharp.API.Client.Domain.Settings; |
| 6 | +using Gotenberg.Sharp.API.Client.Extensions; |
| 7 | +using Microsoft.Extensions.Configuration; |
| 8 | +using Microsoft.Extensions.DependencyInjection; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | + |
| 11 | +// Builds a simple DI container with logging enabled. |
| 12 | +// Client retrieved through the service provider is configured with options defined in appsettings.json |
| 13 | +// Watch the polly-retry policy in action: |
| 14 | +// Turn off gotenberg, run this script and let it fail/retry two or three times. |
| 15 | +// Turn gotenberg back on & the request will successfully complete. |
| 16 | +// Example builds a 1 page PDF from the specified TargetUrl |
| 17 | + |
| 18 | +const string TargetUrl = "https://www.cnn.com"; |
| 19 | +var saveToPath = args.Length > 0 ? args[0] : Path.Combine(Directory.GetCurrentDirectory(), "output"); |
| 20 | +Directory.CreateDirectory(saveToPath); |
| 21 | + |
| 22 | +var services = BuildServiceCollection(); |
| 23 | +var sp = services.BuildServiceProvider(); |
| 24 | + |
| 25 | +var sharpClient = sp.GetRequiredService<GotenbergSharpClient>(); |
| 26 | +var request = await CreateUrlRequest(); |
| 27 | +var response = await sharpClient.UrlToPdfAsync(request); |
| 28 | + |
| 29 | +var resultPath = Path.Combine(saveToPath, $"GotenbergFromUrl-{DateTime.Now:yyyyMMddHHmmss}.pdf"); |
| 30 | + |
| 31 | +using (var destinationStream = File.Create(resultPath)) |
| 32 | +{ |
| 33 | + await response.CopyToAsync(destinationStream); |
| 34 | +} |
| 35 | + |
| 36 | +Console.WriteLine($"PDF created: {resultPath}"); |
| 37 | + |
| 38 | +IServiceCollection BuildServiceCollection() |
| 39 | +{ |
| 40 | + var config = new ConfigurationBuilder() |
| 41 | + .SetBasePath(AppContext.BaseDirectory) |
| 42 | + .AddJsonFile("appsettings.json") |
| 43 | + .Build(); |
| 44 | + |
| 45 | + return new ServiceCollection() |
| 46 | + .AddOptions<GotenbergSharpClientOptions>() |
| 47 | + .Bind(config.GetSection(nameof(GotenbergSharpClient))).Services |
| 48 | + .AddGotenbergSharpClient() |
| 49 | + .Services.AddLogging(s => s.AddSimpleConsole(ops => |
| 50 | + { |
| 51 | + ops.IncludeScopes = true; |
| 52 | + ops.SingleLine = false; |
| 53 | + ops.TimestampFormat = "hh:mm:ss "; |
| 54 | + })); |
| 55 | +} |
| 56 | + |
| 57 | +Task<UrlRequest> CreateUrlRequest() |
| 58 | +{ |
| 59 | + var builder = new UrlRequestBuilder() |
| 60 | + .SetUrl(TargetUrl) |
| 61 | + .ConfigureRequest(b => b.SetPageRanges("1-2")) |
| 62 | + .WithPageProperties(b => |
| 63 | + { |
| 64 | + b.SetPaperSize(PaperSizes.A4) |
| 65 | + .SetMargins(Margins.None); |
| 66 | + }); |
| 67 | + |
| 68 | + return builder.BuildAsync(); |
| 69 | +} |
0 commit comments