使用jsfpd截图并上传到文件服务器
需求
将网页上的html表单,截图并生成pdf ,通过blob 上传到文件服务器
// 获取表单元素dom
const el = document.getElementById('open-reply_form');
const height = el.clientHeight;
// 截图,获取img图像
html2canvas(el).then((canvas) => {
let pageData = canvas.toDataURL('image/jpeg', 1.0);
// 创建pdf ,将图片添加到pdf中
let PDF = new JsPDF('', 'pt', 'a4');
PDF.addImage(pageData, 'JPEG', 40, 40, 515, height + 50);
// 创建blob对象,
var blobPDF = PDF.output("blob");
let file = new File([blobPDF], 'test.pdf',{type:blobPDF.type});
、、 这里的file是file对象,调用oss的上传方法
// this.handleUpload(file);
});
图片在pdf一页
export const generatePdf = async (dom:HTMLElement, len:number, scale:number = 4):Promise<File> => {
const contentWidth = dom.offsetWidth
const contentHeight = dom.offsetHeight
const canvas = await html2canvas(dom, {
allowTaint: true,
scrollY: 0,
scrollX: 0,
width: contentWidth,
height: contentHeight,
useCORS: true, // 开启跨域
scale: scale // window.devicePixelRatio > 1 ? window.devicePixelRatio : 2
})
const pageData = canvas.toDataURL('image/png', 1.0)
const doc = new jsPDF('l', 'px', [contentWidth, contentHeight])
doc.setProperties({ title: '标签打印' })
for (let i = 0; i < len; i++) {
if (i !== len) {
doc.addPage([contentWidth, contentHeight / len])
doc.addImage(pageData, 'png', 0, -i * (contentHeight / len), contentWidth, contentHeight)
}
}
// 删除空白页
doc.deletePage(1)
// doc.save() // 保存文件
// doc.output('dataurlnewwindow') // 浏览器打开预览
const blob = doc.output('blob') as any
const file = new File([blob as any], '1.pdf', {
lastModified: new Date().getTime(),
type: blob.type
})
return Promise.resolve(file)
}

浙公网安备 33010602011771号