要在pdf中居中显示整个DataTable,您可以使用pdfHtml5
插件,并通过CSS样式来调整元素的位置
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.11.4/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.11.4/datatables.min.js"></script>
pdfHtml5
插件,请通过以下链接将其包含在您的项目中:<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.11.4/plugins/pdfHtml5/pdfHtml5.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<!-- 在此处添加数据 -->
</tbody>
</table>
pdfHtml5
插件以导出PDF:$(document).ready(function() {
$('#example').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'pdfHtml5',
text: '导出PDF',
orientation: 'portrait',
pageSize: 'A4',
customize: function (doc) {
// 在此处添加自定义样式和选项
}
}
]
});
});
customize
函数内添加以下代码:customize: function (doc) {
var pageSize = doc.pageSize;
var margin = doc.pageMargins;
// 设置页面大小
doc.pageSize = {
width: pageSize.width,
height: pageSize.height,
margin: '0 auto'
};
// 设置页边距
doc.pageMargins = {
top: 'auto',
bottom: 'auto',
left: margin.left,
right: margin.right
};
}
领取专属 10元无门槛券
手把手带您无忧上云