3

我曾尝试将网页转换为单页 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 页面大小,如屏幕截图实现,但不适用于所有网页。但它在屏幕截图实现中正常工作。你能帮我实现这个目标吗?

4

1 回答 1

4

您可以使用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",
});
于 2018-11-23T10:48:44.957 回答