Bootstrap4下如何用HTML/CSS实现超宽表格垂直显示适配PDF生成
适配PDF的垂直表格实现方案(基于Bootstrap4)
核心逻辑
不改动现有网页端的表格展示效果,利用打印/PDF生成场景的专属CSS规则,把原本横向排布的表格自动切换为垂直堆叠结构,从根本上避免表格宽度撑破PDF页面边界。
完整实现步骤
- 给需要做PDF适配的表格增加专属类名(如
table-pdf-responsive),避免样式污染其他普通表格 - 在样式表中增加打印场景专属的适配规则,利用块级元素重排表格布局
- 给表格的每个数据单元格增加
data-label属性,存储对应列的名称,用于垂直布局时做标签展示
可直接复用的代码示例
<!DOCTYPE html> <html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /> <style> /* 仅在打印/PDF生成时生效的样式,不影响屏幕端展示 */ @media print { /* 把表格所有元素改为块级,脱离默认表格布局 */ .table-pdf-responsive, .table-pdf-responsive thead, .table-pdf-responsive tbody, .table-pdf-responsive tr, .table-pdf-responsive th, .table-pdf-responsive td { display: block; } /* 隐藏原本的横向表头,避免重复占位 */ .table-pdf-responsive thead tr { position: absolute; top: -9999px; left: -9999px; } /* 每条数据独立成块,加边框区分 */ .table-pdf-responsive tr { border: 1px solid #dee2e6; margin-bottom: 1rem; } /* 每个单元格垂直排布,预留左侧标签空间 */ .table-pdf-responsive td, .table-pdf-responsive th[scope="row"] { border: none; border-bottom: 1px solid #dee2e6; position: relative; padding-left: 50%; text-align: right; } /* 用伪元素把列名渲染在单元格左侧作为标签 */ .table-pdf-responsive td::before, .table-pdf-responsive th[scope="row"]::before { position: absolute; left: 1rem; top: 0.5rem; text-align: left; font-weight: bold; content: attr(data-label); } } </style> </head> <body> <table class="table table-bordered table-pdf-responsive"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <th scope="row" data-label="#">1</th> <td data-label="First Name">Mark</td> <td data-label="Last Name">Otto</td> <td data-label="Username">@mdo</td> </tr> <tr> <th scope="row" data-label="#">2</th> <td data-label="First Name">Jacob</td> <td data-label="Last Name">Thornton</td> <td data-label="Username">@fat</td> </tr> <tr> <th scope="row" data-label="#">3</th> <td data-label="First Name">Larry</td> <td data-label="Last Name">the Bird</td> <td data-label="Username">@twitter</td> </tr> </tbody> </table> </body> </html>
注意事项
- 所有适配规则都嵌套在
@media print选择器内,屏幕上打开页面时表格依然保持Bootstrap4默认的横向样式,只有触发打印/生成PDF流程时才会自动切换为垂直布局,不影响现有网页的交互体验 - 无论用浏览器直接打印导出PDF,还是用Puppeteer、wkhtmltopdf这类服务端工具转PDF,这套CSS规则都可以直接生效,不需要额外调整表格HTML结构
- 不要使用Bootstrap自带的
.table-responsive类适配PDF场景,这个类会给表格加横向滚动容器,PDF渲染时滚动容器的超出内容会被直接截断,无法完整展示 - 导出PDF时关闭默认的页眉页脚选项,匹配合理的页面边距,即可达到预期的展示效果
内容的提问来源于stack exchange,提问作者Ousama
相关产品推荐
相关产品推荐

