导出pdf样式
导出内容需要根据导出的样式进行调整,
遇到的问题
1.分页内容会被截断的问题
处理方法:用css的padding来撑开距离,
2.如果将页面元素进行隐藏或者调整透明度的话,会出现没有获取到值而无法导出
处理方法:用绝对定位将top\left的值调大
.pdfshow {
margin: 0;
padding: 0;
position: absolute;
left: -10000px;
top: -10000px;
width: 650px;
}
<div id="pdfContent" v-if="rowPdfData" class="pdfshow">
<div>
<h1>審核單</h1>
<hr />
<h2>信息</h2>
<hr />
<div>
<span>
姓名:{{ rowPdfData.Name }}
</span>
<span>
證件號碼:{{ rowPdfData.Number }}
</span>
</div>
</div>
</div>
导出方法
import html2canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
name: "111",
data() {
return {
rowPdfData: null,
};
},
methods: {
/** 导出按钮操作 */
handleExport(row) {
//根据点击传参进行赋值
this.rowPdfData = row;
setTimeout(() => {
const container = document.getElementById("pdfContent");
this.$nextTick(() => {
html2canvas(container, { scrollY: -window.scrollY, useCORS: true })
.then((canvas) => {
const pdf = new JsPDF({
orientation: "portrait",
unit: "px",
format: "a4",
});
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const imgData = canvas.toDataURL("image/png");
let imgHeight = (canvas.height * pdfWidth) / canvas.width;
let heightLeft = imgHeight;
let position = 0;
// 将内容添加到第一页
pdf.addImage(imgData, "PNG", 0, position, pdfWidth, imgHeight);
heightLeft -= pdfHeight;
// 如果内容溢出,则添加新页面
while (heightLeft > 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(imgData, "PNG", 0, position, pdfWidth, imgHeight);
heightLeft -= pdfHeight;
}
// 添加页码
const totalPages = pdf.internal.getNumberOfPages();
for (let i = 1; i <= totalPages; i++) {
pdf.setPage(i);
//设置页码的字体大小
pdf.setFontSize(10);
// 根据需要调整位置
pdf.text(`${i}/${totalPages}`, pdfWidth - 50, pdfHeight - 10);
}
pdf.save(`news_${new Date().getTime()}.pdf`);
})
.catch((error) => {
console.error("Error: ", error);
});
});
}, 500);
},
},
};
html导出事件
<el-button
type="warning"
plain
con="el-icon-download"
size="medium"
@click="handleExport(scope.row)"
v-hasPermi="['export']"
>导出</el-button>