Detecting printed page size with CSS media queries

2019-03-18 05:00发布

问题:

My app generates printed reports by creating an invisible iframe and then printing it. My latest in a depressingly long list of problems I'm trying to solve is optimizing the CSS for different printed page sizes. IE9 seems to work a bit (but has other issues, like ignoring @page { margin:... }), but no luck at all on FF or Chrome.

My code looks like this:

@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 ...
}

Neither of these rules is being matched, ever, in Chrome or FF. I also tried device-width and device-height, and those didn't work either (they seemed to be reporting the absolute maximum sizes of the printer, rather than the page size). I can't figure out what value "width" and "height" are returning, is there a way to tell?

Is there a reliable way to detect printed page size using media queries? I'm pretty close to concluding that there is simply no way to control printing in any consistent way across browsers, and throwing in the towel on this.