Studiosity / grover

A Ruby gem to transform HTML into PDFs, PNGs or JPEGs using Google Puppeteer/Chromium
MIT License
947 stars 107 forks source link

Failing to render the mobile view on print #218

Open zarembas opened 10 months ago

zarembas commented 10 months ago

I am trying to switch from pdfkit to grover and for whatever reason pdfkit was printing the pages in mobile view by default without any configs. This worked in our favour as the mobile view is more print friendly.

But now I'm struggling to replicate this behaviour.

I tried to changed the viewport to a value that would trigger the mobile view, but this doesn't seem to work:

config.options = {
  format: 'A4',
  margin: {
    top: '1.5cm',
    bottom: '1.5cm',
    left: '1.5cm',
    right: '1.5cm',
  },
  viewport: {
    width: 640,
    height: 900,
  },
  print_background: true,
  scale: 0.8,
  launch_args: ['--disable-dev-shm-usage', '--no-sandbox', '--disable-setuid-sandbox'],
}

Is it possible to achieve this without creating specific views? Am I using the viewport setting incorrectly?

abrom commented 10 months ago

it's not entirely clear what you're asking here, and it's also not entirely clear what you've tried in isolation to other attempts. The viewport option will tell Puppeteer to set the page viewport size (and potentially the device scale factor) https://pptr.dev/api/puppeteer.page.setviewport

Are you saying that you have CSS that uses media queries to reflow your page at different break points?

What happens if you view the page you're trying to convert in Chrome with the width/height set to 640/900. Does that look right?

Then if you go to the print preview ? That's what Puppeteer will essentially return.. Does that look right?

zarembas commented 10 months ago

Sorry for not making it clearer, Are you saying that you have CSS that uses media queries to reflow your page at different break points? this is correct. We are using an external library for that, it triggers the mobile layout at 640 width, but it does seem that even when in mobile view, Chrome prints the full layout of the page. So this might be the way Chrome handles printing and not much Grover can do about it.

abrom commented 10 months ago

It sounds like this CSS library you're using only applies to the screen media type and not print (ie what Grover/puppeteer uses by default). That's what I was trying to ask RE the print preview but your answer was a bit vague.

If that is the case, then adding emulate_media: 'screen' to the Grover options/config would likely fix it.

zarembas commented 10 months ago

I have tried with emulate_media: 'screen', but the viewport's width doesn't make a difference when printing.

abrom commented 9 months ago

Did you try set the width and height but NOT set the page format? I see you're setting it to A4 which will likely overload the width and height options.

This works fine for me:

Grover.new('foo', width: 100, height: 100).to_pdf