我面临着一个令人烦恼的情况。我们尝试在我们的应用程序中使用PuppeteerSharp生成背景PDF,尽管它在开发人员模式下运行良好,但在生产中无法使用。
该应用是WebAPI 2.0网站,.NET4.7.1,Windows 10计算机。我会看到两种环境之间的主要区别是:
我们使用以下代码:
var launchOptions = new LaunchOptions
{
DefaultViewport = new ViewPortOptions
{
Width = 1920,
Height = 1080,
IsLandscape = printOptions.Orientation == PrintOrientation.Landscape
},
ExecutablePath = this._chromiumPath,
Timeout = Timeout,
TransportFactory = AspNetWebSocketTransport.AspNetTransportFactory
};
var browser = await Puppeteer.LaunchAsync(launchOptions)
.ConfigureAwait(false);
var page = await browser.NewPageAsync()
.ConfigureAwait(false);
await page.EmulateMediaTypeAsync(PuppeteerSharp.Media.MediaType.Print)
.ConfigureAwait(false);
await page.GoToAsync(url, Timeout, new[] { WaitUntilNavigation.Networkidle0 })
.ConfigureAwait(false);
await page.WaitForTimeoutAsync(2000)
.ConfigureAwait(false);
var options = new PdfOptions
{
Width = printOptions.Format == PrintFormat.A4 ? "210mm" : "297mm",
Height = printOptions.Format == PrintFormat.A4 ? "297mm" : "420mm",
PrintBackground = true,
Landscape = printOptions.Orientation == PrintOrientation.Landscape,
MarginOptions = new PuppeteerSharp.Media.MarginOptions
{
Top = ".4in",
Bottom = ".4in",
Left = ".4in",
Right = ".4in"
}
};
await page.PdfAsync(outputFile, options)
.ConfigureAwait(false);
return result;
page.GoToAsync
永不返回,并最终超时。
编辑:
false
AspNetWebSocketTransport.AspNetTransportFactory
运输工厂,但似乎也不起作用[如果要在IIS上部署.NET Framework应用程序。您还需要使用PuppeteerSharp.AspNetFramwork并将TransportFactory
设置为浏览器:
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
{
Headless = true,
TransportFactory = AspNetWebSocketTransport.AspNetTransportFactory,
ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)
}).ConfigureAwait(false))