Bootstrap-table打印时需三步修复:①移除.table-responsive容器并重置table类;②用@media print隐藏工具栏/分页栏并强制table-layout:fixed;③导出PDF时用getData()取数据+jsPDF.autoTable渲染,避免DOM截图错位。

打印时表格样式全乱了,怎么用 bootstrap-table 保留列宽和响应式结构?
Bootstrap 默认的响应式表格(.table-responsive)在打印时会失效——滚动容器被忽略、overflow-x: auto 被丢弃、列宽自动坍缩。直接调用 window.print() 只能输出「看起来像表格的碎片」。
真正可用的做法是:打印前临时移除响应式包裹,重置关键 CSS,并强制使用屏幕样式中定义的宽度(而非依赖媒体查询)。示例操作:
// 打印前清理
const $tableWrapper = $('.table-responsive');
const $table = $tableWrapper.find('table');
$tableWrapper.after($table); // 把 table 提到 wrapper 外面
$tableWrapper.remove(); // 干掉破坏打印的容器
$table.removeClass('table-sm').addClass('table'); // 确保基础类存在
同时在打印样式里补一句:@media print { table { width: 100% !important; table-layout: fixed; } td, th { word-break: keep-all; } },否则长文本会撑破列。
如何让 bootstrap-table 的分页/工具栏不进打印内容?
如果你用的是 bootstrap-table 插件(非原生 Bootstrap 表格),它的 .fixed-table-toolbar 和 .fixed-table-pagination 默认会随 table 一起被打印,但实际打印不需要这些。
最稳妥的方式不是靠 JS 隐藏再显示,而是用打印样式直接屏蔽:
@media print {
.fixed-table-toolbar,
.fixed-table-pagination,
.bootstrap-table .columns,
[data-print-exclude] {
display: none !important;
}
}
然后在触发打印前给需要排除的容器加个标记:$('.fixed-table-toolbar').attr('data-print-exclude', 'true')。比反复 toggle display 更可靠,避免 JS 执行时机问题或残留状态。
导出 PDF 比打印更稳?jsPDF + autoTable 怎么接 bootstrap-table 数据?
当用户需要存档、发邮件或跨设备保持格式时,window.print() 不可控(浏览器设置、默认边距、字体替换都会翻车),这时该切到生成 PDF。
别尝试把整个 DOM 截图——表格带分页、固定头、合并单元格时极易错位。正确路径是:从 bootstrap-table 的 getData() 方法取原始数据,交给 autoTable 渲染:
const rows = $table.bootstrapTable('getData');
const doc = new jsPDF();
doc.autoTable({
head: [['ID', '姓名', '状态']],
body: rows.map(r => [r.id, r.name, r.status]),
margin: { top: 10 },
theme: 'grid',
styles: { fontSize: 10 }
});
doc.save('table-data.pdf');
注意两点:一是 head 必须手动构造(bootstrap-table 的列配置不等于打印表头);二是如果表格有服务端分页,得先调 refresh({ silent: true }) 拿全量数据,否则只导出当前页。
打印预览里中文乱码或字体极小?@media print 字体必须显式声明
Chrome / Edge 打印预览常把中文字体回退成宋体,字号缩到 8pt 还不换行——根本原因是打印上下文不继承页面字体栈,且默认禁用 Web 字体。
必须在打印样式中硬编码可信赖字体,并设最小字号:
@media print {
body {
font-family: "Microsoft YaHei", "SimSun", sans-serif !important;
font-size: 12px !important;
}
table {
font-size: 12px !important;
}
th, td {
padding: 4px 6px !important;
}
}
别信“系统会自动适配”,也别用 rem 或 em——打印引擎对相对单位支持极差。所有涉及尺寸、字体、间距的地方,一律用 px 或 pt 显式写死。
复杂点在于:不同浏览器对 @media print 的解析仍有差异,比如 Safari 会忽略某些 !important,而 Firefox 对 word-break 支持更弱。上线前至少要在 Chrome、Edge、Firefox 的打印预览里各点一次「另存为 PDF」看效果。











