-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDefaultPdfService.cs
More file actions
173 lines (149 loc) · 5.03 KB
/
DefaultPdfService.cs
File metadata and controls
173 lines (149 loc) · 5.03 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
// Copyright (c) Argo Zhang (argo@163.com). 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; }
/// <summary>
/// <inheritdoc/>
/// </summary>
public async Task<byte[]> PdfDataAsync(string url)
{
try
{
await using var browser = await LaunchBrowserAsync();
await using var page = await browser.NewPageAsync();
await page.GoToAsync(url);
return await page.PdfDataAsync();
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from URL: {Url}", url);
throw;
}
}
/// <summary>
/// <inheritdoc/>
/// </summary>
public async Task<Stream> PdfStreamAsync(string url)
{
try
{
await using var browser = await LaunchBrowserAsync();
await using var page = await browser.NewPageAsync();
await page.GoToAsync(url);
return await page.PdfStreamAsync();
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from URL: {Url}", url);
throw;
}
}
/// <summary>
/// Export method
/// </summary>
/// <param name="html">html raw string</param>
/// <param name="links"></param>
/// <param name="scripts"></param>
public async Task<byte[]> PdfDataFromHtmlAsync(string html, IEnumerable<string>? links = null, IEnumerable<string>? scripts = 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();
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from HTML content");
throw;
}
}
/// <summary>
/// Export method
/// </summary>
/// <param name="html">html raw string</param>
/// <param name="links"></param>
/// <param name="scripts"></param>
public async Task<Stream> PdfStreamFromHtmlAsync(string html, IEnumerable<string>? links = null, IEnumerable<string>? scripts = 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();
}
catch (Exception ex)
{
Log(ex, "Error generating PDF from HTML content");
throw;
}
}
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 (args.Length != 0)
{
logger.LogInformation(exception, "{Message} | Args: {Args}", message, args);
}
else
{
logger.LogInformation(exception, "{Message}", message);
}
}
}