|
|
|
|
|
我在前文介紹過jQuery將Html表格導出為JSON/CSV/TXT/PDF文件,在導出PDF文件時,可能由于 jsPDF 版本的原因,實現(xiàn)起來比較復(fù)雜,使用起來還不太穩(wěn)定。今天我更新了 jsPDF 插件版本,jQuery實現(xiàn)代碼變得非常簡單。
效果圖
▲網(wǎng)頁表格
▲導出PDF- theme: 'striped'(默認)
▲導出PDF- theme: 'grid'
▲導出PDF- theme: 'plain'
使用介紹
<thead></thead>
標簽里的th
將作為PDF表頭項。
<tbody></tbody>
包含的tr
將作為PDF表行。
table表格需要設(shè)置一個ID屬性值,例如“example”。
<table id="example">
<thead>
<tr>
<th>#</th>
<th>First</th>
<th>Last</th>
<th>Handle</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
需要引用3個js庫文件。
<script src="jquery-3.2.1.min.js"></script>
<script src="jspdf.umd.min.js"></script>
<script src="jspdf.plugin.autotable.js"></script>
jQuery編程:
$('#pdf').on('click',function(){
window.jsPDF = window.jspdf.jsPDF;
var doc = new jsPDF();
doc.autoTable({ html: '#example'});
/* 選擇表格樣式(默認'striped'): 'striped'|'grid'|'plain' */
//doc.autoTable({ html: '#example' , theme: 'striped'});
doc.save('table.pdf');
})
'#pdf'
是HTML“導出PDF”按鈕的ID值,這里賦給它一個鼠標點擊事件。
'table.pdf'
是導出的PDF文件名,可以是任意文件名稱。
'#example'
是HTML表格的ID值。
doc.autoTable({ html: '#example'});
是PDF表格內(nèi)容,可以通過設(shè)置theme的值,自定義表格樣式,如:
/* 設(shè)置表格樣式(默認'striped'): 'striped'|'grid'|'plain' */
doc.autoTable({ html: '#example' , theme: 'striped'});
總結(jié)
本文介紹了jQuery用 jsPDF 插件僅需3行代碼實現(xiàn)表格導出PDF,非常簡單易用,值得推薦。如果你也喜歡該插件,可以收藏本網(wǎng)頁,或者下載源碼備用。
如果你想將Html表格導出JSON、CSV或TXT文件,那么可以參閱下文:
如果你想將HTML網(wǎng)頁轉(zhuǎn)為PDF文件,那么可以參閱下文:
相關(guān)文章