将页面滑动盒子所有内容保存为pdf

一、需求及问题:

页面上有一个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
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值