puppeetersharp 中的单页 PDF

joh*_*ohn 4 c# webautomation google-chrome-headless puppeteer-sharp

我尝试过将网页转换为单页 pdf,但不支持此操作。有什么解决方法可以实现这个要求吗?

我已经尝试过根据 html 内容大小设置 pdf 页面大小。但对于所有网页来说,它并没有按预期工作。我已经使用 EvaluateExpressionAsync 获取了 html 内容大小。下面是我试图实现我的要求的代码片段,但不适用于所有网页(主要是响应式网页)。

int height = await page.EvaluateExpressionAsync("document.body.clientHeight");
Run Code Online (Sandbox Code Playgroud)

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)));
Run Code Online (Sandbox Code Playgroud)

我已将上述高度和宽度设置为 pdf 页面大小,如屏幕截图实现,但不适用于所有网页。但它在屏幕截图实现中工作正常。你能帮助我实现这个目标吗?

har*_*ded 5

您可以使用PdfOptions.HeightPdfOptions.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",
});
Run Code Online (Sandbox Code Playgroud)