2

the requirement of PuppeteerSharp below; I don't know how to use PuppeteerSharp on Windows 7, Is there someone can show me the code ?

The minimum Windows versions supporting the WebSocket library are Windows 8 and Windows Server 2012. Read more. If you need to run Puppeteer-Sharp on Windows 7 you can use System.Net.WebSockets.Client.Managed through the LaunchOptions.WebSocketFactory property.,How to do it?

2 Answers2

4

For those who want more precise answer here is my code that works on 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 with all dependencies can be downloaded from NuGet.

EDIT: Puppeteer have sometimes strange behavior and its better not to wrap its component with using otherwise it hangs in some situations. I have removed this wrappings from code above.

3

Add Reference to “System.Net.WebSockets.Managed.ClientWebSocket”

  private async Task<WebSocket> CreateWebSocket(Uri url, IConnectionOptions options, CancellationToken cancellationToken)
    {
        var result= new ClientWebSocket();
        result.Options.KeepAliveInterval = TimeSpan.Zero;
        await result.ConnectAsync(url, cancellationToken).ConfigureAwait(false);
        return result;
    }