Detect printable page size using CSS media queries

My application creates printed reports, creating an invisible iframe, and then prints it. My last on the frustratingly long list of issues I'm trying to solve is CSS optimization for different printable page sizes. IE9 seems to work a bit (but it has other problems, such as ignoring @page {margin: ...}), but generally not good luck with FF or Chrome.

My code is as follows:

@media print and (width: 210mm) and (height: 297mm) { ... stuff for A4 size ... } @media print and (width: 8.5in) and (height: 11in) { ... stuff for US letter size ... } 

None of these rules match in either Chrome or FF. I also tried the width of the device and the height of the device, and they didn't work either (they seemed to report the absolute maximum sizes of the printer, not the page size). I can’t understand what the meaning of “width” and “height” is returned, is there any way to say?

Is there a reliable way to determine the size of a printed page using media queries? I’m pretty close to the conclusion that it’s simply impossible to control the print in any form in browsers and throw a towel at it.

+6
source share
1 answer

You seem to be working hard on the fact that you don't have to do a lot of work ... Try printing specific areas of the page like this ...

Add these classes to your stylesheet ...

 <style media="screen"> .noPrint{ display: block; } .yesPrint{ display: block !important; } </style> <style media="print"> .noPrint{ display: none; } .yesPrint{ display: block !important; } </style> 

And then put the classes where you need them. Just like a tip ... just placing the .yesPrint class .yesPrint not print the areas you need. You will also have to put .noPrint in areas that you do not want to print.

I tested this on Chrome, IE10, IE9 and IE8, and it works great.

-2
source

Source: https://habr.com/ru/post/959274/


All Articles