puppeteer-sharp
puppeteer-sharp copied to clipboard
Puppeteer Sharp timeout on second request to download to PDF on ASP MVC 5
Description
I'm implementing the following code to use Puppeteer Sharp for generating PDF on an ASP MVC 5 application, on the first request it works fine, but on any following request it takes too long to load any url and crashes, I tried disabling the headless and get the same result, I created this as an extension method for the controller
Complete minimal example reproducing the issue
using PuppeteerSharp;
using System.Threading.Tasks;
using System.Web.Hosting;
namespace System.Web.Mvc
{
public static class MvcPdfExtensions
{
public static async Task<ActionResult> ViewAsPdf(this Controller controller,
string fileName,
string actionName,
string controllerName,
object routeValues = null)
{
var HostPath = HostingEnvironment.MapPath("~/Content/");
var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions()
{
Path = HostPath
});
var revisionInfo = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false,
ExecutablePath = revisionInfo.ExecutablePath,
});
var page = await browser.NewPageAsync();
var cookies = controller.Request.Cookies.AllKeys;
foreach (var cookieKey in cookies)
{
var cookie = controller.Request.Cookies[cookieKey];
await page.SetCookieAsync(new CookieParam
{
Name = cookie.Name,
Value = cookie.Value,
Domain = controller.Request.Url.Authority
});
}
try
{
var url = controller.Url.Action(actionName, controllerName, routeValues, "http");
var waitOptions = new WaitUntilNavigation[]
{
WaitUntilNavigation.Load
};
await page.GoToAsync(url, null, waitOptions);
var pdfOptions = new PdfOptions
{
PrintBackground = true
};
var file = await page.PdfDataAsync(pdfOptions);
return new FileContentResult(file, "application/pdf")
{
FileDownloadName = fileName
};
}
catch (Exception e)
{
return new ContentResult {
Content = $"Error generando PDF: Tipo: {e.Source} Mensaje: {e.Message}"
};
}
finally {
await page.DisposeAsync();
await browser.CloseAsync();
}
}
}
}
Expected behavior:
I expect the PDF View to be download any time.
Actual behavior:
The second and subsequent request timeout and the page never loads.
Versions
- PuppeteerSharp version 5.0.0
- .NET framework 4.6.1
I'm currently trying to achieve the same thing as you but unfortunately I haven't been able to get anything to work at all. I've tried the code you posted but get an exception at await page.GoToAsync(url, null, waitOptions);
that I can't seem to figure out. Have you run into this problem too? And if so, can you share how to fix it?
@BramvdBogaard yes, I get the same error it throws a timeout exception on the second request on that line, I keep changing the timeout value but it still throws the same exception
Closed due to inactivity. Feel free to reopen it if needed.