1

I use Puppeteer to generate receipts in PDF. For each receipt, width is always the same, but height changes, according to the article count in the order.

For now, I'm using the article count to approximate the required height for my receipt. It kind of works, but it's not perfect and is a dirty way to do (you can notice useless blank space at the bottom of the picture bellow).

Is there way to tell Puppeteer : "Please automatically find the right PDF height, according to the HTML content, in order to NOT generate useless blank space" ?

enter image description here

David Dahan
  • 10,576
  • 11
  • 64
  • 137

1 Answers1

4

As I understand correctly you are using width and height options of page.pdf(options) method (unfortunately you didn't provide your code). You may try to get height value of the loaded web page by evaluating JS function on the page. For example ...

const pageHeight = await page.evaluate(() => { window.innerHeight; });
const result = await page.pdf({ height: pageHeight  + 'px' });
Slava Ivanov
  • 6,666
  • 2
  • 23
  • 34
  • 1
    Well, the idea was to evaluate JS function(s) on the page and I don't believe you cannot get height of the document. What you need is JS to get correct height of the web page in Chrome browser. Is this would help: [How to get height of entire document with JavaScript?](https://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript). Please give a try. – Slava Ivanov Oct 15 '18 at 13:34
  • Consider changing the snippet so the evaluate function returns the value, else `pageHeight` will be undefined – Julián M. May 26 '21 at 17:24
  • @JuliánM. The snippet provided is just the piece of code that I even didn't run. It demonstrates approach should be taken. I was not intended to provide a robust, error-proof solution. If you concern about `window.innerHeight` return, for current chrome/firefox browsers supported by Puppeteer, this always returns the number. If you concern about `page.evaluate`, which may resolve to `undefined` use different methods to check it and do something, for example, log it, throw an exception or use the default value (`pageHeight = pageHeight || 0`). Anyway, this is out of the scope of the answer. – Slava Ivanov May 26 '21 at 17:43