这两天我被击中了,设置列宽以使用 jsPDF 生成 PDF。
我能够使用 html 表中的 jsPDF 库生成 pdf,但我遇到了重叠列的问题。因为我想在工作表中显示 20 列。我已将选项纵向更改为横向,并在导出脚本选项中设置宽度 5000 以及 html 表格宽度。
请帮助我,从 jsPDF 设置 pdf 列宽。谢谢
最佳答案
我在 4 天前遇到了同样的问题并且能够修复它。我在下面提供了示例代码供您理解。
我假设要求将 html 表(下面提到的表 1,有 3 行或更多行)导出为 PDF 格式。我们将为这 3 行以上的行设置单元格/列宽以及字体和字体类型。
第一行将是标题 - 所以应用了粗体。我为第二行和第三行应用了不同的样式以了解可用的样式。如果你想为每一列应用不同的列宽 - 你可以这样做还有..
希望下面的代码是可读的和不言自明的。如果您有任何问题,请告诉我
$(document).on("click", "#btnExportToPDF", function () {
var table1 =
tableToJson($('#table1').get(0)),
cellWidth = 35,
rowCount = 0,
cellContents,
leftMargin = 2,
topMargin = 12,
topMarginTable = 55,
headerRowHeight = 13,
rowHeight = 9,
l = {
orientation: 'l',
unit: 'mm',
format: 'a3',
compress: true,
fontSize: 8,
lineHeight: 1,
autoSize: false,
printHeaders: true
};
var doc = new jsPDF(l, '', '', '');
doc.setProperties({
title: 'Test PDF Document',
subject: 'This is the subject',
author: 'author',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'author'
});
doc.cellInitialize();
$.each(table1, function (i, row)
{
rowCount++;
$.each(row, function (j, cellContent) {
if (rowCount == 1) {
doc.margins = 1;
doc.setFont("helvetica");
doc.setFontType("bold");
doc.setFontSize(9);
doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
}
else if (rowCount == 2) {
doc.margins = 1;
doc.setFont("times ");
doc.setFontType("italic"); // or for normal font type use ------ doc.setFontType("normal");
doc.setFontSize(8);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
}
else {
doc.margins = 1;
doc.setFont("courier ");
doc.setFontType("bolditalic ");
doc.setFontSize(6.5);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i); // 1st=left margin 2nd parameter=top margin, 3rd=row cell width 4th=Row height
}
})
})
doc.save('sample Report.pdf'); })
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data; }
关于javascript - 如何使用jsPDF设置列宽以生成pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23060563/