Reputation:
I am using JSPDF to generate pdf files in our site. I have some content which can vary in length each time. How can I automatically adjust JsPdf parameters to add new page every time the content overflows on first page
Upvotes: 1
Views: 4966
Reputation: 359
I have different solution. Since the above said answers were bit complicated to implement, you can use the jspdf-autotable.
npm install jspdf-autotable
Import this and add the following
const doc = jsPDF({ orientation: 'p' });
doc.autoTable({
theme: 'plain',
headStyles: { halign: 'center', fontSize: 18, fontStyle: 'bold' },
head: [[docName]],
body: [
[docData],
],
});
return doc.save(`${docName}.pdf`);
};
Where head is the document header that I needed, and docData is the data to be added. It will generate pdf document with multiple pages automatically.
Upvotes: 0
Reputation: 308
Hye,
it's a bit later and answer is not perfect but it does the job for me (in ES6):
private createNewPdf() {
this.positionY = MARGIN_TOP; // margin top
this.pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', lineHeight: 1 });
}
// convert mm to fontSize
private setTextHeight(this.textHeight) {
let fontSize = this.textHeight * 4;
this.pdf.setFontSize(fontSize);
}
private addText(text) {
this.setTextHeight(textHeight);
if (this.positionY + textHeight > (this.pdf.internal.pages.height - MARGIN_BOTTOM)) {
this.addPage();
}
this.pdf.text(MARGIN_LEFT, this.positionY + this.textHeight, text);
this.positionY += textHeight;
}
private addPage() {
this.pdf.addPage();
this.positionY = MARGIN_TOP;
}
So after you just have to:
this.textHeight = 3; // mm
this.positionY = 0; // position of previous text
this.pdf = null;
this.createNewPdf();
this.addText('My first text');
this.addText('My second text');
...
And if there is more text than place, page will be automatically added with MARGIN_TOP (you have to define this)
Upvotes: 2