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

发布于:2024-11-03 ⋅ 阅读:(102) ⋅ 点赞:(0)

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);
    });
  });
}


网站公告

今日签到

点亮在社区的每一天
去签到