puppeetersharp中的单页PDF



我曾尝试将网页转换为单页pdf,但没有支持。有什么变通方法可以满足这一要求吗?

我已经尝试过从html内容大小设置pdf页面大小。但它并没有像预期的那样为所有网页工作。我已经使用EvaluateExpressionAsync获得了html内容大小。以下是我试图实现我的需求的代码片段,但并不适用于所有的网页(大多数是响应网页(。

int height = await page.EvaluateExpressionAsync("document.body.clientHeight");

dynamic metrics = await Client.SendAsync("Page.getLayoutMetrics").ConfigureAwait(false); 
var width = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(metrics.contentSize.width.Value))); 
var height = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(metrics.contentSize.height.Value)));

我已经像屏幕截图实现一样将上面的高度和宽度设置为pdf页面大小,但这并不适用于所有网页。但它在屏幕截图实现中运行正常。你能帮我做到这一点吗?

您可以使用PdfOptions.Height和PdfOptions.Width.您可能会发现它不是像素完美的,但这在Chromium方面比在Puppeteer方面更重要。

await page.SetViewportAsync(new ViewPortOptions()
{
Height = 1024,
Width = 1280
});
await page.GoToAsync("https://github.com/kblok/puppeteer-sharp/");
int height = await page.EvaluateExpressionAsync<int>("document.body.offsetHeight");
int width = await page.EvaluateExpressionAsync<int>("document.body.offsetWidth");
await page.PdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "test.pdf"), new PdfOptions
{
Width = width.ToString() + "px",
Height = height.ToString() + "px",
});