1

我们使用 PuppeteerSharp 添加用户下载我们应用程序的 PDF 的功能。不幸的是,有时会启动大量 Chromium 进程,并且在服务器重新启动之前不会停止。

通常,当用户下载 pdf 时,会启动 5 个 Chromium 进程,下载完成后这些进程会消失。

这是我们的代码:

private static LaunchOptions launchOptions = new LaunchOptions
{
    ExecutablePath = chromepath,
    Headless = true,
    DefaultViewport = ViewPortOptions
};

public static void ExportPdf(string url, string location)
{
    try
    {
        Task<string> task = Task.Run<string>(async () => await ExportPdfASync(url, location)));
        task.Wait();
    }
    catch (Exception)
    {
        // Exception handling
    }
}

public static async Task<string> ExportPdfASync(string url, string location)
{
    using (var browser = await Puppeteer.LaunchAsync(LaunchOptions))
    using (var page = await browser.NewPageAsync())
    {
        await page.SetViewportAsync(new ViewPortOptions() { Width = 1440, Height = 990, IsMobile = false, DeviceScaleFactor = 1.0 });

        await page.SetJavaScriptEnabledAsync(true);
        await page.GoToAsync(url);
        await page.WaitForTimeoutAsync(1500);

        var marginOptions = new MarginOptions()
        {
            Top = "10mm",
            Left = "10mm",
            Right = "10mm",
            Bottom = "10mm"
        };

        var pdfOptions = new PdfOptions()
        {
            PrintBackground = true,
            Format = PaperFormat.A4,
            MarginOptions = marginOptions,
            Landscape = landscape
        };
        await page.PdfAsync(location, pdfOptions);
    }

    return "";
}

浏览器和页面位于 using 块中,因此即使出现错误,也应将其处理掉。

有没有人有这个问题的解决方案?我们和我们的服务器会非常高兴;)

在此处输入图像描述

4

1 回答 1

1

尝试这个:

public static async Task<string> ExportPdfASync(string url, string location)
{
 try
 {
   using (var browser = await Puppeteer.LaunchAsync(LaunchOptions))
   using (var page = await browser.NewPageAsync())
   {
    await page.SetViewportAsync(new ViewPortOptions() { Width = 1440, Height = 990, IsMobile = false, DeviceScaleFactor = 1.0 });

    await page.SetJavaScriptEnabledAsync(true);
    await page.GoToAsync(url);
    await page.WaitForTimeoutAsync(1500);

    var marginOptions = new MarginOptions()
    {
        Top = "10mm",
        Left = "10mm",
        Right = "10mm",
        Bottom = "10mm"
    };

    var pdfOptions = new PdfOptions()
    {
        PrintBackground = true,
        Format = PaperFormat.A4,
        MarginOptions = marginOptions,
        Landscape = landscape
    };
    await page.PdfAsync(location, pdfOptions);
  }
  }
  catch (Exception ex)
  {
  }
  finally {
    browser.CloseAsync();
    page.CloseAsync();
  }
  return "";
}
于 2020-07-23T11:29:15.287 回答