包含表格、图表和图形的Web应用程序通常包含将数据导出为PDF的选项。你有没有想过,作为一个用户,当你点击那个按钮时,幕后发生了什么?
作为开发人员,如何让PDF输出看起来更专业?大多数免费的在线PDF导出器实际上只是将HTML内容转换为PDF,而不进行任何额外的格式化,这会使数据难以阅读。如果你也能添加诸如页眉和页脚、页码或重复的表列标题等内容呢?像这样的小点缀,对把一份看起来很业余的文件变成一份优雅的文件有很大的帮助。
最近,我探索了几种生成PDF的解决方案,并建立了这个Demo程序[1]来展示结果。所有的代码也可以在Github[2]上找到。让我们开始吧!
window
对象公开了一个 print
方法,所以我们可以写一个简单的JavaScript函数,并将其附加到我们的一个按钮上,就像这样:function downloadPDFWithBrowserPrint() {
window.print();
}
document.querySelector('#browserPrint').addEventListener('click', downloadPDFWithBrowserPrint);
function downloadPDFWithjsPDF() {
var doc = new jspdf.jsPDF('p', 'pt', 'a4');
doc.html(document.querySelector('#styledTable'), {
callback: function (doc) {
doc.save('MLB World Series Winners.pdf');
},
margin: [60, 60, 60, 60],
x: 32,
y: 32,
});
}
document.querySelector('#jsPDF').addEventListener('click', downloadPDFWithjsPDF);
<canvas>
元素上的图像,然后 jsPDF 接收该画布内容并将其保存。function downloadPDFWithPDFMake() {
var tableHeaderText = [...document.querySelectorAll('#styledTable thead tr th')].map(thElement => ({ text: thElement.textContent, style: 'tableHeader' }));
var tableRowCells = [...document.querySelectorAll('#styledTable tbody tr td')].map(tdElement => ({ text: tdElement.textContent, style: 'tableData' }));
var tableDataAsRows = tableRowCells.reduce((rows, cellData, index) => {
if (index % 4 === 0) {
rows.push([]);
}
rows[rows.length - 1].push(cellData);
return rows;
}, []);
var docDefinition = {
header: { text: 'MLB World Series Winners', alignment: 'center' },
footer: function(currentPage, pageCount) { return ({ text: `Page ${currentPage} of ${pageCount}`, alignment: 'center' }); },
content: [
{
style: 'tableExample',
table: {
headerRows: 1,
body: [
tableHeaderText,
...tableDataAsRows,
]
},
layout: {
fillColor: function(rowIndex) {
if (rowIndex === 0) {
return '#0f4871';
}
return (rowIndex % 2 === 0) ? '#f2f2f2' : null;
}
},
},
],
styles: {
tableExample: {
margin: [0, 20, 0, 80],
},
tableHeader: {
margin: 12,
color: 'white',
},
tableData: {
margin: 12,
},
},
};
pdfMake.createPdf(docDefinition).download('MLB World Series Winners');
}
document.querySelector('#pdfmake').addEventListener('click', downloadPDFWithPDFMake);
'pdf'
),以及要使用的HTML内容。根据你的需要,还有数百种不同配置的选择,但基本配置是一个很好的起点。function downloadPDFWithDocRaptor() {
DocRaptor.createAndDownloadDoc('YOUR_API_KEY_HERE', {
test: true, // test documents are free, but watermarked
type: 'pdf',
name: 'MLB World Series Winners',
document_content: document.querySelector('html').innerHTML,
})
}
document.querySelector('#docRaptor').addEventListener('click', downloadPDFWithDocRaptor);
@page
选择器,就像这样。@page {
margin-top: 80px;
margin-bottom: 80px;
@top {
content: "MLB World Series Winners"
}
@bottom {
/* 具有计数器功能的页脚可插入页面计数器 */
content: "Page " counter(page) " of " counter(pages)
}
}
原文:https://levelup.gitconnected.com/how-to-convert-html-tables-into-beautiful-pdfs-eac2ce4c77de
作者:Tyler Hawkins
临走前留下,今天的福利
- END -
走心的分享更容易被抽中~
开奖时间 下期文末
点赞 + 在看 + 留言
下一个幸运儿就是你
👇