首先看需求,頁面上會渲染出一個表格,可以預覽爲pdf、並且導出爲pdf:
當點擊預覽pdf
按鈕,則在iframe
的地方預覽:
點擊導出pdf
按鈕,則導出這個table爲pdf:
實現過程:
首先看看官網API,這個庫可以將table
導出爲很多形式:
我主要說的是導出爲pdf格式,要看看它的分支jsPDF-AutoTable的API介紹,用法和配置項很詳細,主要看examples
文件夾裏面的示例:
// html 樣式就不寫了,自行修改
<button id="download-btn" class="pure-button">導出 PDF</button>
<button id="preiew-btn" class="pure-button">預覽pdf</button>
<!-- 預覽區 注意加上寬高尺寸, 你可以開始隱藏它,點擊預覽再顯示 -->
<div id="wrapper">
<iframe id="output"></iframe>
</div>
<!-- table -->
<table id="basic-table" border="1">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Country</th>
<th>IP-address</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Donna</td>
<td>Moore</td>
<td>[email protected]</td>
<td>China</td>
<td>211.56.242.221</td>
</tr>
<tr>
<td>2</td>
<td>Janice</td>
<td>Henry</td>
<td>[email protected]</td>
<td>Ukraine</td>
<td>38.36.7.199</td>
</tr>
<tr>
<td>3</td>
<td>Ruth</td>
<td>Wells</td>
<td>[email protected]</td>
<td>Trinidad and Tobago</td>
<td>19.162.133.184</td>
</tr>
<tr>
<td>4</td>
<td>Jason</td>
<td>Ray</td>
<td>[email protected]</td>
<td>Brazil</td>
<td>10.68.11.42</td>
</tr>
<tr>
<td>5</td>
<td>Jane</td>
<td>Stephens</td>
<td>[email protected]</td>
<td>United States</td>
<td>47.32.129.71</td>
</tr>
<tr>
<td>6</td>
<td>Adam</td>
<td>Nichols</td>
<td>[email protected]</td>
<td>Canada</td>
<td>18.186.38.37</td>
</tr>
</tbody>
</table>
// js
<script src="libs/jspdf.min.js"></script>
<script src="../dist/jspdf.plugin.autotable.js"></script>
<script>
// 導出pdf
document.getElementById('download-btn').onclick = function () {
update(true);
};
// 預覽
document.getElementById('preiew-btn').onclick = function () {
update()
}
function update(shouldDownload) {
shouldDownload = shouldDownload || false; // 預覽還是導出
var doc = new jsPDF('p', 'pt'); // 初始化示例,更多配置項看官網api
doc.text("From HTML", 40, 50); // 表title、距離左邊距離、距離上邊距離
var res = doc.autoTableHtmlToJson(document.getElementById("basic-table")); // 獲取當前表格的數據
doc.autoTable(res.columns, res.data, {startY: 60}); // 渲染數據,列、數據、距離上邊距離,更多配置項看官網api
if (shouldDownload) {
doc.save('tableName.pdf'); // 導出名爲tableName.pdf的文件
} else {
// doc.output('datauristring'):pdf預覽的地址,一段base64地址
document.getElementById("output").src = doc.output('datauristring');
}
}
</script>
就醬~