【问题标题】:How to center fixed width table on page horizontally? jsPDF with autotable如何在页面上水平居中固定宽度的表格?带有自动表格的jsPDF
【发布时间】:2019-08-19 10:38:27
【问题描述】:

我正在使用带有 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();
});

【问题讨论】:

    标签: javascript pdf jspdf jspdf-autotable


    【解决方案1】:

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

    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');
    

    【讨论】:

    • 这正是我正在寻找的解决方案,非常感谢!
    【解决方案2】:

    用 div 元素包裹表格。

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

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

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

    【讨论】:

    • 我没有在我的应用程序中使用 标签,我想通过 JS 从我将传递的数据中生成它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2017-11-29
    • 2020-05-28
    • 1970-01-01
    • 2013-11-14
    • 2011-06-27
    • 2017-01-23
    相关资源
    最近更新 更多