-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDefaultPdfService.cs
More file actions
231 lines (204 loc) · 7.14 KB
/
DefaultPdfService.cs
File metadata and controls
231 lines (204 loc) · 7.14 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using Microsoft.Extensions.Logging;
using PuppeteerSharp;
using System.Net;
namespace BootstrapBlazor.Components;
/// <summary>
/// 默认 Html to Pdf 实现
/// </summary>
class DefaultPdfService(ILogger<DefaultPdfService> logger) : IHtml2Pdf
{
/// <summary>
/// 获得/设置 WebProxy 对象用于网络请求代理
/// <para>Get or set the WebProxy object for network request proxy</para>
/// </summary>
public IWebProxy? WebProxy { get; set; }
public async Task<byte[]> PdfDataAsync(string url, PdfOptions? options = null)
{
try
{
await using var browser = await LaunchBrowserAsync();
await using var page = await browser.NewPageAsync();
await page.GoToAsync(url);
return await page.PdfDataAsync(GetOptions(options));
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from URL: {Url}", url);
throw;
}
}
public async Task<Stream> PdfStreamAsync(string url, PdfOptions? options = null)
{
try
{
await using var browser = await LaunchBrowserAsync();
await using var page = await browser.NewPageAsync();
await page.GoToAsync(url);
return await page.PdfStreamAsync(GetOptions(options));
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from URL: {Url}", url);
throw;
}
}
public async Task<byte[]> PdfDataFromHtmlAsync(string html, IEnumerable<string>? links = null, IEnumerable<string>? scripts = null, PdfOptions? options = null)
{
try
{
await using var browser = await LaunchBrowserAsync();
await using var page = await browser.NewPageAsync();
await page.SetContentAsync(html);
await AddStyleTagAsync(page, links);
await AddScriptTagAsync(page, scripts);
return await page.PdfDataAsync(GetOptions(options));
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from HTML content");
throw;
}
}
public async Task<Stream> PdfStreamFromHtmlAsync(string html, IEnumerable<string>? links = null, IEnumerable<string>? scripts = null, PdfOptions? options = null)
{
try
{
await using var browser = await LaunchBrowserAsync();
await using var page = await browser.NewPageAsync();
await page.SetContentAsync(html);
await AddStyleTagAsync(page, links);
await AddScriptTagAsync(page, scripts);
return await page.PdfStreamAsync(GetOptions(options));
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from HTML content");
throw;
}
}
private static PuppeteerSharp.PdfOptions GetOptions(PdfOptions? options)
{
return options == null ? new PuppeteerSharp.PdfOptions() : new PuppeteerSharp.PdfOptions
{
Landscape = options.Landscape,
PrintBackground = options.PrintBackground,
Format = GetFormat(options.Format),
MarginOptions = GetMarginOptions(options.MarginOptions),
DisplayHeaderFooter = options.DisplayHeaderFooter,
Scale = options.Scale
};
}
private static PuppeteerSharp.Media.MarginOptions? GetMarginOptions(MarginOptions options) => new PuppeteerSharp.Media.MarginOptions
{
Top = options.Top,
Bottom = options.Bottom,
Left = options.Left,
Right = options.Right
};
private static PuppeteerSharp.Media.PaperFormat GetFormat(PaperFormat format)
{
if (format == PaperFormat.A0)
{
return PuppeteerSharp.Media.PaperFormat.A0;
}
else if (format == PaperFormat.A1)
{
return PuppeteerSharp.Media.PaperFormat.A1;
}
else if (format == PaperFormat.A2)
{
return PuppeteerSharp.Media.PaperFormat.A2;
}
else if (format == PaperFormat.A3)
{
return PuppeteerSharp.Media.PaperFormat.A3;
}
else if (format == PaperFormat.A4)
{
return PuppeteerSharp.Media.PaperFormat.A4;
}
else if (format == PaperFormat.A5)
{
return PuppeteerSharp.Media.PaperFormat.A5;
}
else if (format == PaperFormat.A6)
{
return PuppeteerSharp.Media.PaperFormat.A6;
}
else if (format == PaperFormat.Letter)
{
return PuppeteerSharp.Media.PaperFormat.Letter;
}
else if (format == PaperFormat.Legal)
{
return PuppeteerSharp.Media.PaperFormat.Legal;
}
else if (format == PaperFormat.Tabloid)
{
return PuppeteerSharp.Media.PaperFormat.Tabloid;
}
else if (format == PaperFormat.Ledger)
{
return PuppeteerSharp.Media.PaperFormat.Ledger;
}
else
{
return new PuppeteerSharp.Media.PaperFormat(format.Width, format.Height);
}
}
private static async Task AddStyleTagAsync(IPage page, IEnumerable<string>? links = null)
{
var styles = new List<string>();
if (links != null)
{
styles.AddRange(links);
}
foreach (var link in styles)
{
await page.AddStyleTagAsync(link);
}
}
private static async Task AddScriptTagAsync(IPage page, IEnumerable<string>? scripts = null)
{
var tags = new List<string>();
if (scripts != null)
{
tags.AddRange(scripts);
}
foreach (var script in tags)
{
await page.AddScriptTagAsync(script);
}
}
private static LaunchOptions CreateOptions() => new() { Headless = true, Args = ["--no-sandbox", "--disable-setuid-sandbox", "--disable-web-security"] };
private async Task<IBrowser> LaunchBrowserAsync()
{
var browserFetcher = new BrowserFetcher
{
WebProxy = WebProxy
};
Log(null, "Ready to start downloading browser");
var browser = await browserFetcher.DownloadAsync();
Log(null, $"Browser downloaded successfully. installed browser {browser.BuildId}");
var options = CreateOptions();
Log(null, "Start your browser", "--no-sandbox", "--disable-setuid-sandbox", "--disable-web-security");
return await Puppeteer.LaunchAsync(options);
}
private void Log(Exception? exception, string? message, params object?[] args)
{
if (logger.IsEnabled(LogLevel.Information))
{
if (args.Length != 0)
{
logger.LogInformation(exception, "{Message} | Args: {Args}", message, args);
}
else
{
logger.LogInformation(exception, "{Message}", message);
}
}
}
}