-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathHtmlConvert.linq
61 lines (48 loc) · 1.97 KB
/
HtmlConvert.linq
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
<Query Kind="Program">
<NuGetReference Version="2.0.0-alpha0002" Prerelease="true">Gotenberg.Sharp.API.Client</NuGetReference>
<Namespace>Gotenberg.Sharp.API.Client</Namespace>
<Namespace>Gotenberg.Sharp.API.Client.Domain.Builders</Namespace>
<Namespace>Gotenberg.Sharp.API.Client.Domain.Builders.Faceted</Namespace>
<Namespace>Gotenberg.Sharp.API.Client.Extensions</Namespace>
<Namespace>System.Net.Http</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
</Query>
static string ResourcePath = @$"{Path.GetDirectoryName(Util.CurrentQueryPath)}\Resources\Html\ConvertExample\";
static Random Rand = new Random(Math.Abs( (int) DateTime.Now.Ticks));
async Task Main()
{
var path = await CreateFromHtml(@"D:\Gotenberg\Dumps");
var info = new ProcessStartInfo { FileName = path, UseShellExecute = true };
Process.Start(info);
path.Dump("Done");
}
public async Task<string> CreateFromHtml(string destinationDirectory)
{
var sharpClient = new GotenbergSharpClient("http://localhost:3000");
var builder = new HtmlRequestBuilder()
.AddAsyncDocument(async doc =>
doc.SetBody(await GetHtmlFile("body.html"))
.SetFooter(await GetHtmlFile("footer.html"))
).WithDimensions(dims => dims.UseChromeDefaults())
.WithAsyncAssets(async
assets => assets.AddItem("ear-on-beach.jpg", await GetImageBytes())
).SetConversionBehaviors(b =>
b.AddAdditionalHeaders("hello", "from-earth")
).ConfigureRequest(b=> b.SetPageRanges("1"));
var request = await builder.BuildAsync();
var resultPath = @$"{destinationDirectory}\GotenbergFromHtml-{Rand.Next()}.pdf";
var response = await sharpClient.HtmlToPdfAsync(request);
using (var destinationStream = File.Create(resultPath))
{
await response.CopyToAsync(destinationStream);
}
return resultPath;
}
static Task<byte[]> GetImageBytes()
{
return File.ReadAllBytesAsync($@"{ResourcePath}\ear-on-beach.jpg");
}
static Task<byte[]> GetHtmlFile(string fileName)
{
return File.ReadAllBytesAsync($@"{ResourcePath}\{fileName}");
}