DataTable打印预览加载完成后打印方向选择选项消失问题求助
修复DataTables打印预览方向选项消失问题
问题根源
你代码里给表格设置font-size: absolute是错误的——absolute是定位属性,不是字体大小的有效值,这种无效CSS会导致打印窗口的样式解析异常,干扰浏览器打印控件的正常显示。另外,自定义打印内容时如果没有显式指定打印页面的方向规则,也可能导致浏览器隐藏方向选项。
修复步骤
- 修正无效CSS:将表格的字体大小设置改为合法值(比如
12px),删除错误的absolute设置。 - 添加打印媒体查询样式:在
customize函数中,给打印窗口的头部添加专门的打印样式,显式定义页面方向规则,确保浏览器能识别并保留方向选项。 - 避免破坏默认布局:确保自定义添加的内容不会覆盖或干扰浏览器内置的打印控件容器。
修改后的代码示例
var printButton = $@" {{ text: '<i class=""fa fa-print"" style=""font-size: 15px; ""></i>', className: 'print', extend: 'print', footer: true, title: $('.page-title').html(), exportOptions: {{ columns: ':visible' }}, customize: function(win) {{ // 添加打印专用样式 var style = win.document.createElement('style'); style.textContent = ` @media print {{ @page {{ size: auto; /* 让浏览器自动适配,也可指定landscape/portrait */ margin: 1cm; }} body {{ font-size: 12px; }} }} `; win.document.head.appendChild(style); // 自定义头部内容 $(win.document.body) .prepend( '<div style=""display: flex; flex-direction: column; align-items: left;"">' + '<div style=""font-size: 30px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;"">' + '{companyInfo.Name}' + '</div>' + '<div style=""font-size: 15px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; margin-left: 10px;"">' + '{companyInfo.Address1}' + '</div>' + '<div style=""font-size: 15px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; margin-left: 10px;"">' + '{companyInfo.Address2}' + '</div>' + '<div style=""font-size: 15px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; margin-left: 10px;"">' + '{companyInfo.Address3}' + '</div>' + '</div>' ); $(win.document.body).find('.page-title') .css('font-size', '20px'); $(win.document.body).find('table') .addClass('compact') .css('font-size', '12px'); // 修正为合法字体大小 }} }} ";
额外说明
如果需要默认指定打印方向,可以把@page里的size: auto改成size: landscape(横向)或size: portrait(纵向),这样浏览器打印预览会默认显示对应方向,同时保留方向切换选项。
内容的提问来源于stack exchange,提问作者VIDYADEEP S
相关产品推荐
相关产品推荐

