Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When printing, the browsers don't know how wide the paper is

I've got a bit of a problem with printing a html document. Apparently the browsers don't know how wide the paper is, and they make wild and inaccurate guesses!

The document is responsive, showing different layouts at different widths, and I hoped that when printing, they would take the styles for about 700 or 800 pixels, but they don't. Not all of them.

Tried to change the media queries from sizes in px to physical units (pt or cm) but that did not help.

I also ensured that the browsers were all set to use the same paper size, orientation, and margins, and that they didn't have any "scale to fit page" flags set.

Here is a fiddle: http://jsfiddle.net/MrLister/Lc5kE/show
If you resize the window a bit, you will see that it shows how wide it is. Then when you hit Print Preview, that's when it goes wrong: IE says the width of an A4 is 18..19cm, Mozilla says 20..21cm and Chrome says 14..15cm. Opera is the worst of all: it doesn't look at the paper at all, it just takes the size of the window on the screen.
And like I said, there is no difference whether you use physical units or pixels or em.

So am I doing something wrong? Am I overlooking something? Is there something I can do, short of forcing a fixed paper size (like A4) down people's throats?

Edit: after some more testing, I found that IE takes the printer margins into account, while Mozilla does not. So if you set all the margins to zero, IE and Mozilla both report 20..21cm for the width. The others are still very uncooperative though.

like image 730
Mr Lister Avatar asked Nov 29 '13 09:11

Mr Lister


1 Answers

The easiest way will be to use '%' instead of 'cm'.

The problem, as far as the JSFiddle example goes, is that you have not specified the changed widths of the divs inside the '@media' min-width/max-width queries. Since the widths of the given divs are fixed. the page itself is not responsive. You can understand your problem better, by resizing your browser and seeing that the overflows are shown... Thus in short your page is not responsive to fit the print page.

Also, just to fit the divs within the print page, you could use the following css code:

@media print{
 html,
 body{
  width: 100%;
 }
 body div{
  max-width: 100%;
 }
}

(Note: this code wont work on your JSFiddle example, since the styles of 'div's were specified inline.)

Still not satisfied? Use css transform to scale the page to fit the print page. When using this, don't forget to set 'transform-origin: 0% 0%;'.

For example, the largest of your divs is 31cm wide, and the margins is usually 1cm. So, within a print-page of width between 16cm and 17cm, you could scale it to 50% and manually fit the page to the print-page.

The former method is the best practice though. Gud Luck.

like image 185
BlackPanther Avatar answered Sep 20 '22 17:09

BlackPanther