Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting printed page size with CSS media queries

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.

like image 917
neilw Avatar asked Dec 03 '13 20:12

neilw


People also ask

How do I check my screen size in CSS?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.

What is @media used for in CSS?

The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used.

What is @media print in CSS?

You can use CSS to change the appearance of your web page when it's printed on a paper. You can specify one font for the screen version and another for the print version. You have seen @media rule in previous chapters. This rule allows you to specify different style for different media.


1 Answers

Just try this code May be this can fixed your problem.

<page size="A4"></page>

Css

@page {
  size: A4;
  margin: 0;
}
page {
  background: white;
  display: block;
  margin: 0 auto;
  margin-bottom: 12px;
  box-shadow: 0 0 5px rgba(0,0,0,0.5);
}
page[size="A4"] {  
  width: 210mm;
  height: 297mm; 
}

@media print {
  body {
    margin: 0;
    box-shadow: 0;
    background: rgb(204,204,204); 
  }
}
like image 197
codeuix Avatar answered Sep 26 '22 08:09

codeuix