我们使用PuppeteerSharp来增加用户下载我们应用程序PDF的能力。不幸的是,有时启动了大量的Chromium进程,直到服务器重启后才停止。
通常,当用户下载pdf时,会启动5个铬处理,而下载完成后这些处理会消失。
这是我们的代码:
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块中,因此即使出现错误也应将其丢弃。
有人对此问题有解决方案吗?我们和我们的服务器将非常高兴;)
答案 0 :(得分:0)
尝试一下:
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 "";
}