对于那些想要更准确答案的人来说,我的代码适用于 Windows 7。
private async void SaveToFile(string url)
{
try
{
WebSocketFactory webSocketFactory = CreateWebSocket;
LaunchOptions launchOptions = new LaunchOptions()
{
Headless = true,
WebSocketFactory = webSocketFactory
};
var browser = await Puppeteer.LaunchAsync(launchOptions, product: Product.Chrome);
var page = await browser.NewPageAsync();
await page.GoToAsync(url);
await page.PdfAsync("MyPdf.pdf", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4 });
Task.WaitAll(new Task[2] {
page.DisposeAsync().AsTask(),
browser.DisposeAsync().AsTask() });
}
}
}
catch (Exception objException)
{
CommonMsgBox.Warning(objException.Message, "Error");
}
}
private static async Task<System.Net.WebSockets.WebSocket> CreateWebSocket(Uri url, IConnectionOptions options, CancellationToken cancellationToken)
{
var result = new System.Net.WebSockets.Managed.ClientWebSocket();
result.Options.KeepAliveInterval = TimeSpan.Zero;
await result.ConnectAsync(url, cancellationToken).ConfigureAwait(false);
return result;
}
System.Net.WebSockets.Managed
可以从 NuGet 下载所有依赖项。
编辑:Puppeteer 有时会有奇怪的行为,最好不要用它包裹它的组件,using
否则它会在某些情况下挂起。我已经从上面的代码中删除了这个包装。