4

I have tried to convert a web page to single page pdf, but there is no support for this. Is there any workaround to achieve this requirement?

I have already tried by setting the pdf page size from html content size. But it is not working as expected for the all the webpage. I have get the html content size using EvaluateExpressionAsync. Below are the code snippets i have tried to achieve my requirement, but not working for all the web pages (mostly responsive webpages).

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

and

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)));

I have set the above height and width to pdf page size like the screenshot implementation, but the does not work for all the web page. But it is working properly in Screenshot implementation. Can you help me to achieve this?

hardkoded
  • 18,915
  • 3
  • 52
  • 64
john
  • 57
  • 1
  • 5

1 Answers1

5

You can use the PdfOptions.Height and PdfOptions.Width.You might find that it's not pixel perfect but that's more on the Chromium's side than on Puppeteer's.

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",
});
hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • I have tried the provided example code snippet and it is working properly for some website and it is not working as expected for responsive web pages. For example please convert this link, it will generate multiple page pdf instead of single page. URL = https://stackoverflow.com/questions/14001483/document-body-clientheight-not-working-javascript – john Nov 26 '18 at 10:06
  • Yeah, but that's more a Chorium issue than a Puppeteer one. – hardkoded Nov 26 '18 at 12:01
  • 1
    I think if you can file this issue on Google`s Puppeteer they can give you some timelines or where to report it – hardkoded Nov 26 '18 at 12:26