繁体   English   中英

如何在页面上水平居中固定宽度的表格? 带有自动表的 jsPDF

[英]How to center fixed width table on page horizontally? jsPDF with autotable

我正在使用带有自动表的 jsPDF,我试图在生成的 pdf 页面上以固定宽度居中表格。 我似乎找不到解决方案,我看到的所有地方都是全宽的,我不希望我的桌子是全宽的。 我尝试使用边距选项,但它不是很精确,而且我不完全确定如何计算 A4 的边距以水平居中我的表格。

截屏: 在此处输入图像描述

document.querySelector(".report-btn").addEventListener("click", () => {
  const pdfDoc = new jsPDF();
  const list = createListforPdf(); // function to generate list

  pdfDoc.autoTable({
    theme: "grid",
    tableWidth: 100,
    styles: { halign: "center" },
    columnStyles: {
      0: { cellWidth: 85, halign: "left" },
      1: { cellWidth: 15 }
    },

    head: [["MRZ Check number", "is OK?"]],
    body: [[list[0], "YES"], [list[1], "NO"]]
  });

  pdfDoc.save();
});

用div元素包装表格。

<div class="table-container">
    <table id="my-table"><!--...--></table>
</div>

在CSS中,编写类以使表在容器内居中。

div.table-container {
    display: flex;
    justify-content: center;
}

您可以通过以下方式计算边距:

let doc = new jsPDF();

let wantedTableWidth = 100;
let pageWidth = doc.internal.pageSize.width;
let margin = (pageWidth - wantedTableWidth) / 2;

doc.autoTable({
    head: [['Name', 'Country']],
    body: [
        ['Leon', 'Sweden'],
        ['Magnus', 'Norway'],
        ['Juan', 'Argentina'],
    ],
    margin: {left: margin, right: margin}
});

doc.save('table.pdf');

我这样解决了这个问题:

var pageWidth = receiptPDF.internal.pageSize.width || receiptPDF.internal.pageSize.getWidth(); var wantedTableWidth = 60;
var marginTable = (pageWidth - wantedTableWidth) / 2

receiptPDF.autoTable({
  margin: {top: 0, right: marginTable, left: marginTable, bottom: 0 },
  cellWidth: 'auto',
  minCellHeight: 2
}

请注意,cellWidth 属性必须设置为“auto”才能工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM