使用JQuery和jsPDF从HTML生成PDF

时间:2018-07-19 09:53:31

标签: javascript php jquery jspdf

以下是使用jQuery和jspdf从HTML生成PDF的代码。单击“下载pdf”按钮时不会发生任何事件。 jQuery:

$(document).ready(function() {
  $('#download_pdf').click(function(e) {
    e.preventDefault();
    var pdf = new jsPDF('p', 'pt', 'letter'),
      source = $('#table_stock')[0],
      specialElementHandlers = {
        '#table_stock': function(element, renderer) {
          return true
        }
      }
    margins = {
      top: 60,
      bottom: 60,
      left: 40,
      width: 522
    };
    pdf.fromHTML(
      source, margins.left, margins.top, {
        'width': margins.width,
        'elementHandlers': specialElementHandlers
      },
      function(dispose) {
        pdf.save('Stockreport.pdf');
      },
      margins
    )
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock_report" id="table_stock"></div>
<button id="download_pdf" class="btndownloadt_stock_report btn btn-primary">Download PDF</button>

1 个答案:

答案 0 :(得分:2)

您没有按如下方式包含lib,因此请添加lib,因为没有错误。

jQuery('.custom_button').click(function (e) {

    var d = "http://example.com/example.pdf";

    var url = '/wp-admin/admin-post.php';
    var filename = 'test.zip';
    var params = 'action=files_download&custom_file_names='+d;
    var request = new XMLHttpRequest();
    request.open('POST', url, true);
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.responseType = 'blob';
    request.onload = function() {
        var link = document.createElement('a');
        document.body.appendChild(link);
        link.href = window.URL.createObjectURL(request.response);
        link.download = filename;
        link.click();
    };
    request.send(params);

});

另一件事就是只使用<script src='https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js'></script> ,不需要$('#table_stock'),如果您使用的是[0] class,则使用selector