-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
81 lines (67 loc) · 2.07 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using Microsoft.Playwright;
using System.Reflection;
// Used for basic validation of the format.
var validPrintFormats = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Letter", "Legal", "Tabloid", "Ledger",
"A0", "A1", "A2", "A3", "A4", "A5", "A6",
};
using var playwright = await Playwright.CreateAsync();
IBrowser? browser = null;
IBrowserContext? browserContext = null;
var builder = WebApplication.CreateSlimBuilder(args);
var app = builder.Build();
app.MapGet("/", () => TypedResults.Ok(Assembly.GetExecutingAssembly().GetName().Version));
// Single end-point to convert HTML to PDF content.
app.MapPost("/", async Task<IResult> (Html2PdfRequest request) =>
{
if (browser?.IsConnected == false)
{
if (browserContext is not null)
{
await browserContext.DisposeAsync();
browserContext = null;
}
await browser.DisposeAsync();
browser = null;
}
browser ??= await playwright.Chromium.LaunchAsync(new()
{
Args = ["--disable-dev-shm-usage", "--no-first-run", "--no-sandbox", "--disable-setuid-sandbox"],
Headless = true,
});
browserContext ??= await browser.NewContextAsync(new()
{
ViewportSize = new() { Height = 800, Width = 600 },
AcceptDownloads = false,
JavaScriptEnabled = false,
BypassCSP = true,
ServiceWorkers = ServiceWorkerPolicy.Block,
});
var page = await browserContext.NewPageAsync();
try
{
await page.SetContentAsync(request.Html ?? string.Empty, new() { Timeout = 30000 });
var pdfBytes = await page.PdfAsync(new()
{
Format = validPrintFormats.Contains(request.Format ?? string.Empty) ? request.Format : "Letter",
PrintBackground = true,
Scale = 1,
Path = null
});
return TypedResults.File(pdfBytes, "application/pdf", (request.FileName ?? "file") + ".pdf");
}
catch (Exception ex)
{
return TypedResults.BadRequest(ex.ToString());
}
finally
{
if (!page.IsClosed)
{
await page.CloseAsync();
}
}
});
await app.RunAsync();
sealed record Html2PdfRequest(string Html, string? FileName, string? Format = "Letter");