使用CSS媒体查询检测打印页面大小 [英] Detecting printed page size with CSS media queries

查看:607
本文介绍了使用CSS媒体查询检测打印页面大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序通过创建不可见的iframe然后打印来生成打印报告。我最新的一个令人沮丧的问题,我想解决的是优化CSS的不同的打印页面大小。 IE9似乎工作有点(但有其他问题,例如忽略@page {margin:...}),但没有运气在FF或Chrome。

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

正在匹配,在Chrome或FF。我也尝试了设备宽度和设备高度,那些没有工作(他们似乎报告的绝对最大尺寸的打印机,而不是页面大小)。我不知道什么值width和height返回,有没有办法告诉?

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.

推荐答案

你似乎做了很多工作,你不需要做很多工作...尝试打印页面的某些区域,像这样.. 。

You seem to be doing a lot of work for something you don't need to do a lot of work for... Try printing certain areas of the page like this...

将这些类添加到样式表中

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

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

然后把类放在你需要的地方。正如一个建议...只是把 .yesPrint 类不会打印你需要的区域。您还必须在不想打印的区域中插入 .noPrint

And then put the classes where you need them. Just as a piece of advice... only putting the .yesPrint class will not print the areas that you need. You'll also have to put .noPrint in the areas you don't want to print.

我已经在Chrome,IE10,IE9和IE8上测试过这个工具。

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

这篇关于使用CSS媒体查询检测打印页面大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆