Div 中的文本/字体大小在 Firefox 的打印模式下与在“正常”模式下不同

Text/font size in Div different in print mode in Firefox than in "normal" mode

本文关键字:模式 正常 Firefox 文本 字体 Div 打印      更新时间:2023-09-26

情况如下:我制作了一个允许用户创建抽认卡的工具(存储在mysql库中)。现在,如果要打印抽认卡,脚本会生成一个表格,其中 td 具有固定宽度(以 px 为单位),里面是一个div,其中包含用户为抽认卡正面或背面输入的文本。由于文本量可能会有所不同,因此如有必要,将减小标准字体大小。看起来像这样:

HTML:
<table class="cardtable">
    <tr>
        <td class="cardtd wrap"><div class="adjustsize"> 
                  Shorter Text here in the first td
            </div></td>
        <td class="cardtd wrap"><div class="adjustsize"> 
                  Might be a loooooooooooooooong text here in the second td
            </div></td>
    </tr>
</table>

CSS:
table.cardtable {
    table-layout:fixed;
    border-collapse:collapse;
    page-break-before:always;
}
td.cardtd {
    width: 470px;
    max-width: 470px;
    height:300px;
    max-height:300px;
    font-size:11px;
    padding-top:20px;
    padding-bottom:20px;
    padding-left:22px;
    padding-right:22px;
}
td.wrap { /*if a word is too long -> break it */
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}
div.adjustsize {
   display:block;
   max-width:inherit;
   max-height:inherit;
   font-size:100%;
   overflow:hidden;
   vertical-align:middle;
   text-align:center; 
}

Js:
<script type='text/javascript'>
    $(function() {
        $('div.adjustsize').each(function() {
            var fontSize = 100;
            while (this.scrollHeight > $(this).height() && fontSize > 0) {
                fontSize -= 0.2;
                $(this).css('font-size', fontSize + '%');
            }
        });
    });
</script>

所以现在我最大的问题是:当我让脚本在 Firefox 中渲染表格时,JS 会正确调整字体的大小,这意味着如果文本一开始太长,JS 会减小字体大小,直到它适合div。但是,如果我想在之后打印页面,在 Firefox 的打印模式下,文本突然超过了div,这意味着它的一部分不再可见(缩放 100%)!

PS:我选择了td的宽度和高度,以或多或少地将其放在A4纸上。

编辑:感谢您的建议。我尝试使用@media css 样式,并使用 window.onbeforeprint 和 window.onafterprint 函数检查了我能想象到的每个 css 值,看看是否有任何变化,但什么都没有。每个值(包括填充,边距,字母间距等)都与以前完全相同,但是当我在Firefox中按"打印"时,预览会压缩/缩小某些元素,导致文本占用更多行。奇怪的是,当在 Firefox 中使用某些插件允许您在打印模式下编辑代码时,该插件会正确显示渲染的元素。

最后,问题似乎只发生在打印预览(以及稍后的实际打印)中,但我在代码中找不到相应的"错误"或不匹配。

我读了几篇关于 dpi 的文章,打印预览是否有可能使用与我的浏览器不同的 dpi,因为它试图模仿/预览打印机(其 dpi 与屏幕不同)?

检查此链接链接

    var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
    if (mql.matches) {
        console.log('onbeforeprint equivalent');
    } else {
        console.log('onafterprint equivalent');
    }
});

 var beforePrint = function() {
               //your code 
            };
            var afterPrint = function() {
              //your code 
            };

您可以使用打印 css

<link rel="stylesheet" type="text/css" href="your file css here .css" media="print" />