You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript新手用html2canvas转HTML表格为PDF遇元素未绑定文档错误

解决HTML表格转PDF时的“Element is not attached to a Document”错误

错误根源分析

  1. removeContainer: true 导致元素脱离DOM
    html2canvas的该配置会在渲染完成后将目标元素从文档中移除,后续代码里form.width(cache_width)尝试操作已脱离文档的元素,直接触发“Element is not attached to a Document”错误。

  2. 事件参数未传递
    createPDF函数中使用event.preventDefault()但未接收event参数,会引发event未定义的隐性错误。


修复后的完整代码

HTML部分(仅优化按钮类型,避免默认提交行为)

<button type="button" id="create_pdf" class="btn btn-primary">Generate Report</button>

<div class="container-fluid px-4" id="transactions">
    <img src="pl-removebg-preview.png" class="img-fluid logo" style="margin-top:5%; margin-left:35%;">
    <h4 style="justify-content:center; text-align: center; margin-top:5%;">Transactions report from <b id="from"> </b> to <b id="to"> </b></h4>
    <div class="row my-5">
        <div class="col table-responsive">
            <table id="myTable" class="table table-striped" style="width:100%">
                <thead>
                    <tr>
                        <th>Merchant Name</th>
                        <th>Distributor Number</th>
                        <th>Provider</th>
                        <th>Customer Merchant</th>
                        <th>Date</th>
                        <th>Status</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody id="client_data">
                </tbody>
                <tfoot>
                    <tr>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th>Total</th>
                        <th id="total"></th>
                    </tr>
                </tfoot>
            </table>
            <nav class="pagination-container">
                <div id="pagination-numbers">
                </div>
            </nav>
        </div>
    </div>
</div>

JavaScript部分(核心修复)

$(document).ready(function () {
  var form = $('#transactions'),
    cache_width = form.width(),
    a4 = [610.28, 841.89]; // A4纸像素尺寸

  $('#create_pdf').on('click', function (event) {
    $('body').scrollTop(0);
    createPDF(event); // 传递事件对象
  });

  function createPDF(event) {
    event.preventDefault();
    getCanvas().then(function (canvas) {
      var img = canvas.toDataURL("image/png"),
          doc = new jsPDF({
            unit: 'px',
            format: 'a4'
          });
      doc.addImage(img, 'PNG', 20, 20);
      doc.save('Pay_Lesotho_Report.pdf');
      form.width(cache_width); // 恢复元素原宽度
    });
  }

  function getCanvas() {
    // 临时修改元素宽度适配PDF
    form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
    // 移除removeContainer配置,保留元素在DOM中
    return html2canvas(form, {
      imageTimeout: 2000
    });
  }
});

可选优化:避免修改原元素样式

如果不想临时改动原元素的宽度,可以克隆元素进行渲染,完成后移除克隆体:

function getCanvas() {
  // 克隆目标元素并添加到页面
  var clonedForm = form.clone().appendTo('body');
  clonedForm.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
  
  return html2canvas(clonedForm, {
    imageTimeout: 2000
  }).then(function(canvas) {
    clonedForm.remove(); // 渲染完成后清理克隆元素
    return canvas;
  });
}

内容的提问来源于stack exchange,提问作者Nosi Chefane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:08:11