如何使用 JsPDF-autoTable 在每个页面的顶部添加徽标?

How to add a logo to the top of each page using JsPDF-autoTable?

JsPdf-autoTable 是一款很棒的软件,非常容易让基础知识发挥作用。

现在我想在每个页面的顶部添加一个徽标和一些文本,并在每个页面上添加一个 page X of Y 页脚,但我不知道如何做。我想从 URL(我网站上的本地文件)获取徽标图像。

有什么简单的例子吗?我想我是用 JsPdf 做的,而不是 JsPdf-autoTable。

该方法接受一个参数:

doc.autoTable(options);

options,是一个对象,可以在文档中查看它的属性here.

options 对象接受 hooks。您正在寻找 didDrawPage 挂钩,它将启用页眉和页脚的插入。

didDrawPage: (HookData) => {} - Called after the plugin has finished drawing everything on a page. Can be used to add headers and footers with page numbers or any other content that you want on each page there is an autotable.

注意:didDrawPage钩子在v3以下的版本中被命名为addPageContent

demo 中已经有关于如何执行此操作的示例。代码如下:

var doc = new jsPDF();
var totalPagesExp = "{total_pages_count_string}";

doc.autoTable({
    head: headRows(),
    body: bodyRows(40),
    didDrawPage: function (data) {
        // Header
        doc.setFontSize(20);
        doc.setTextColor(40);
        doc.setFontStyle('normal');
        if (base64Img) {
            doc.addImage(base64Img, 'JPEG', data.settings.margin.left, 15, 10, 10);
        }
        doc.text("Report", data.settings.margin.left + 15, 22);

        // Footer
        var str = "Page " + doc.internal.getNumberOfPages()
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
        }
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        var pageSize = doc.internal.pageSize;
        var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
        doc.text(str, data.settings.margin.left, pageHeight - 10);
    },
    margin: {top: 30}
});

// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
    doc.putTotalPages(totalPagesExp);
}

return doc;

base64Img 变量必须有你的图片,我只用 base64 图像测试过,据说你可以添加一个超链接,如果你有本地图片,它会起作用。


代码段:

(function() {

  function imgToBase64(url, callback) {
    if (!window.FileReader) {
      callback(null);
      return;
    }
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
      var reader = new FileReader();
      reader.onloadend = function() {
        callback(reader.result.replace('text/xml', 'image/jpeg'));
      };
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
  }

  var base64Img;

  // Convert the image to base64
  // imgToBase64("https://placehold.it/50x50", function(base64) {
  //   base64Img = base64;
  // });

  // Static base64 for example purposes
  base64Img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyBAMAAADsEZWCAAAAG1BMVEXMzMyWlpaqqqq3t7exsbGcnJy+vr6jo6PFxcUFpPI/AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAQUlEQVQ4jWNgGAWjgP6ASdncAEaiAhaGiACmFhCJLsMaIiDAEQEi0WXYEiMCOCJAJIY9KuYGTC0gknpuHwXDGwAA5fsIZw0iYWYAAAAASUVORK5CYII='

  var headRows = function() {
    return [{
      id: "ID",
      name: "Name",
    }];
  };

  var bodyRows = function(rowCount) {
    rowCount = rowCount || 10;
    let body = [];

    for (var i = 1; i <= rowCount; i++) {
      body.push({
        id: i,
        name: "Name " + i
      });
    }

    return body;
  }

  function generate() {
    var doc = new jsPDF();
    var totalPagesExp = "{total_pages_count_string}";

    doc.autoTable({
      head: headRows(),
      body: bodyRows(40),
      didDrawPage: function(data) {
        // Header
        doc.setFontSize(20);
        doc.setTextColor(40);
        doc.setFontStyle('normal');
        if (base64Img) {
          doc.addImage(base64Img, 'JPEG', data.settings.margin.left, 15, 10, 10);
        }
        doc.text("Example", data.settings.margin.left + 15, 22);

        // Footer
        var str = "Page " + doc.internal.getNumberOfPages()
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
          str = str + " of " + totalPagesExp;
        }
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        var pageSize = doc.internal.pageSize;
        var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
        doc.text(str, data.settings.margin.left, pageHeight - 10);
      },
      margin: {
        top: 30
      }
    });

    // Total page number plugin only available in jspdf v1.0+
    if (typeof doc.putTotalPages === 'function') {
      doc.putTotalPages(totalPagesExp);
    }

    doc.save("headerandfooterexample.pdf");
  }

  document.getElementById('download-btn').addEventListener('click', generate);

})()
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
<script src="https://unpkg.com/jspdf-autotable"></script>
<button id="download-btn">Download PDF</button>