欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 前端将网页转换为pdf并支持下载与上传

前端将网页转换为pdf并支持下载与上传

2025/5/7 9:23:30 来源:https://blog.csdn.net/hu_666666/article/details/143451967  浏览:    关键词:前端将网页转换为pdf并支持下载与上传

1.pdf下载


handleExport() {const fixedH = document.getElementById("fixed-h");const pageOne = document.getElementById("mix-print-box-one");const pageTwo = document.getElementById("mix-print-box-two");fixedH.style.height = '30vh';pageOne.style.display = 'block';pageTwo.style.display = 'block';// 禁止滚动document.body.addEventListener('touchmove', this.preventDefaultScroll, { passive: false });document.body.addEventListener('wheel', this.preventDefaultScroll, { passive: false });html2canvas(pageOne).then((canvasOne) => {const imgOne = canvasOne.toDataURL("image/png");const pdf = new jsPDF();const propsOne = pdf.getImageProperties(imgOne);const widthOne = pdf.internal.pageSize.getWidth();const heightOne = (propsOne.height * widthOne) / propsOne.width;pdf.addImage(imgOne, "PNG", 0, 0, widthOne, heightOne);html2canvas(pageTwo).then(canvasTwo => {const imgTwo = canvasTwo.toDataURL("image/png");const propsTwo = pdf.getImageProperties(imgTwo);const widthTwo = pdf.internal.pageSize.getWidth();const heightTwo = (propsTwo.height * widthTwo) / propsTwo.width;pdf.addPage(); // 分页pdf.addImage(imgTwo, "PNG", 0, 0, widthTwo, heightTwo);const title = `${this.formOne.application}测试的.pdf`;pdf.save(title);fixedH.style.height = 'auto';pageOne.style.display = 'none';pageTwo.style.display = 'none';// 恢复滚动document.body.removeEventListener('touchmove', this.preventDefaultScroll);document.body.removeEventListener('wheel', this.preventDefaultScroll);});});
}

2.pdf上传


handleUploadPdf(id) {const element = document.getElementById("myElementId");html2canvas(element).then((canvas) => {const imgData = canvas.toDataURL("image/png");const pdf = new jsPDF();const imgProps = pdf.getImageProperties(imgData);const pdfWidth = pdf.internal.pageSize.getWidth();const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);// 将 PDF 转换为 Blob 对象const blob = pdf.output("blob");// 上传文件const fileName = "测试的.pdf";const formData = new FormData();formData.append("file", blob, fileName);uploadPdf(formData).then((res) => {// 将pdf地址传给后端uploadPdfUrl({id,fileName,path: res.fileName,});console.log("上传成功", res.url);});});
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词