通过html2canvas、jsPDF将页面截取生成pdf文件

  1. 安装插件
  2. 安装html2canvas
    npm i html2canvas
    安装jspdf
    npm i jspdf
  3. 封装导出文件函数
    /**
     * 生成pdf
     * @param name 
     * @param title 
     */
    const htmlToPdf = async (name, title) => {
        // 开启loading效果
        reportDialogRef.value.startLoading();
        const ele = document.querySelector('#' + name);
        const childrenBox = ele.children;
        const pdf = new jsPDF('', 'pt', 'a4');
    
        for (let i = 0; i < childrenBox.length; i++) {
            const res = await html2canvas(childrenBox[i], {
                dpi: 400, // 设置 DPI
                useCORS: true,
                allowTaint: true,
                scale: 4  // 设置缩放比例
            });
            const pageData = res.toDataURL('image/jpeg', 1.0);
    
            const contentWidth = res.width;
            const contentHeight = res.height;
    
            // A4 页面尺寸(pt)
            const a4Width = 595.28;
            const a4Height = 841.89;
    
            // 计算图像在 A4 页面中的宽高比
            const imgAspectRatio = contentWidth / contentHeight;
            let imgWidth, imgHeight;
    
            // 根据 A4 尺寸和图像宽高比计算宽高
            if (imgAspectRatio > a4Width / a4Height) {
                imgWidth = a4Width;
                imgHeight = a4Width / imgAspectRatio;
            } else {
                imgHeight = a4Height;
                imgWidth = a4Height * imgAspectRatio;
            }
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
            if (i < childrenBox.length - 1) {
                pdf.addPage(); // 添加新页面
            }
        }
    
        // 将 PDF 转换为 Blob
        // const pdfBlob = pdf.output('blob');
        // const formData = new FormData();
        // formData.append('sample_id', reportForm.value.sample_id);
        // formData.append('report_version', reportForm.value.report_version);
        // formData.append('pdf_file', pdfBlob, `${title}.pdf`); // 添加 Blob 和文件名
        // formData.append('report_info', JSON.stringify(reportForm.value.reportInfo));
        // // 提交表单数据
        // fetchGeneratePdf(formData).then(res => {
        //     Notification({
        //         message: res.msg
        //     });
        //     reportDialogRef.value.endLoading();
        // }).catch(err => {
        //     console.error('生成 PDF 失败:', err);
        //     reportDialogRef.value.endLoading();
        // }).finally(()=>{
        //     requestTableData()
        // })
    };
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值