一、需求及问题:
页面上有一个id="mold-list"的盒子,里面根据moldList循环渲染了Mold组件,所以id="mold-list"的盒子为固定高度,超出滑动,宽度方面为根据屏幕自适应。现在需要点击按钮将id="mold-list"的盒子里所有内容保存为pdf文件
html:
<div class="mold-list" id="mold-list">
<Mold
v-for="(item, index) in moldList"
:key="item.id"
:width="item.width"
:height="item.height"
:componentList="item.componentList"
/>
</div>
<div class="action-list">
<el-button @click="reset">重置</el-button>
<el-button type="primary" @click="print">打印</el-button>
</div>
scss:
.mold-list {
display: flex;
flex-wrap: wrap;
width: 100%;
height: 665px;
padding: 5px;
overflow: auto;
}
问题:
1、超出高度部分没有获取到
2、屏幕宽度过宽时,盒子自适应变宽后,pdf文件里横向也会缺失
实现函数:(需安装插件html2canvas 和 jspdf)
import html2canvas from "html2canvas"
import jsPDF from "jspdf"
const print = async () => {
pageLoading.value = true
// 获取需要转换的元素
const moldList = document.getElementById(`mold-list`)
// 存储原始样式以便恢复
const originalStyle = {
width: moldList.style.width,
height: moldList.style.height,
overflow: moldList.style.overflow
}
// 临时更改元素的样式以显示所有内容
moldList.style.width = "1016px"
moldList.style.height = "auto"
moldList.style.overflow = "visible"
// 等待 DOM 更新
await new Promise(resolve => setTimeout(resolve, 0))
// 使用 html2canvas 捕获元素
const canvas = await html2canvas(moldList)
// 恢复原始样式
moldList.style.width = originalStyle.width
moldList.style.height = originalStyle.height
moldList.style.overflow = originalStyle.overflow
// 使用 jsPDF 创建 PDF
const pdf = new jsPDF({
orientation: "p",
unit: "px",
format: [canvas.width, canvas.height] // 设置 PDF 页面大小与 canvas 匹配
})
pdf.addImage(canvas.toDataURL("image/jpeg", 1.0), "JPEG", 0, 0, canvas.width, canvas.height)
// 创建下载链接并触发下载
const a = document.createElement("a")
a.href = URL.createObjectURL(pdf.output("blob"))
a.download = `排产方案.pdf`
a.click()
pageLoading.value = false
}