先在html引入cdn
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
script里面写
//导出pdf var pdfs = document.getElementsByClassName("importPdf"); for (var i = 0; i < pdfs.length; i++) { pdfs[i].addEventListener('click', htmlToPdf); } function htmlToPdf() { // 获取HTML元素 const element = document.getElementById("dataTable"); const options = { dpi: 192, scale: 1, backgroundColor: "#F1F6FE" }; const elsSte = document.getElementById('cloneTable'); // 将元素转换为canvas对象 new Promise((resolve, reject) => { html2canvas(element, options).then(canvas => { resolve(canvas); }).catch(error => { reject(error); }); }).then(canvas => { var contentWidth = canvas.width; var contentHeight = canvas.height; var pdf = new jsPDF('1', 'pt', [contentWidth, contentHeight]); var pageData = canvas.toDataURL('image/jpeg', 1.0); pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight); pdf.save("deno.pdf"); }).catch(error => { console.error(error); }); }
html里面就写
<span class="importPdf">导出pdf</span>
<table id="dataTable">
<tr>
<th>标题</th>
</tr>
<tr>
<td>
<textarea style="width: 160px" class="multiline-textarea">标题内容</textarea>
</td>
</tr>
</table>
文字重叠就在对应的元素上面加上letter-spacing: 1px;还是重叠就设置多点2px,4px试一下
发现textarea 有的标签内容只显示一点没有显示全部。调试了好久还是显示不全换个思路得到dom,替换标签显示
// 获取HTML元素
const element = document.getElementById("dataTable");
var newSex = element.cloneNode(true);
// 将select标签进行复制
const newDom = newSex.innerHTML.replace(/textarea/g, 'input');
const objE = document.createElement("table");
const objBox = document.getElementById("clone_box");
objE.id = 'cloneTable';
objE.innerHTML = newDom;
objBox.append(objE)
const elsSte = document.getElementById('cloneTable');
new Promise((resolve, reject) => {
html2canvas(elsSte, options).then(canvas => {
resolve(canvas);
}).catch(error => {
reject(error);
});
}).then(canvas => {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
var pdf = new jsPDF('1', 'pt', [contentWidth, contentHeight]);
var pageData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight);
pdf.save("车型.pdf");
elsSte.style.display = 'none';
}).catch(error => {
console.error(error);
});
//html文件里面得把clone的div在body里面加上
<div id="clone_box"></div>
//style里面这样不会显示,导出的时候才可以显示子级的内容
#clone_box {
opacity: 0;
}
换成input或者p标签什么的。但是得看元素的style替换成对应的元素才行。你不可能内联的替换成块状的。可以自己添加样式什么的
不想显示什么元素就在对应的元素上面加data-html2canvas-ignore属性就行。
<!-- 操作列--> <td class="action-column" data-html2canvas-ignore> <button type="button" class="remove-row" data-index="{{ loop.index }}">删除</button> </td>
右侧赞助一下 代码改变世界一块二块也是爱