Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getTextDimensions should automatically infer numberOfLines if maxTextWidth is provided #2824

Merged
merged 7 commits into from Aug 10, 2020
21 changes: 17 additions & 4 deletions src/modules/cell.js
Expand Up @@ -193,15 +193,28 @@ import { jsPDF } from "../jspdf.js";
);
}

text = Array.isArray(text) ? text : [text];

const maxWidth = options.maxWidth
if (maxWidth > 0){
if (typeof text === 'string'){
text = this.splitTextToSize(text, maxWidth)
} else if (Object.prototype.toString.call(text) === "[object Array]") {
text = this.splitTextToSize(text.join(" "), maxWidth)
}
} else {
// Without the else clause, it will not work if you do not pass along maxWidth
text = Array.isArray(text) ? text : [text];
}

for (var i = 0; i < text.length; i++) {
tempWidth = this.getStringUnitWidth(text[i], { font: font }) * fontSize;
if (width < tempWidth) {
width = tempWidth;
}
if (width !== 0) {
amountOfLines = text.length;
}
}

if (width !== 0) {
amountOfLines = text.length;
}

width = width / scaleFactor;
Expand Down
12 changes: 6 additions & 6 deletions test/specs/cell.spec.js
Expand Up @@ -10,16 +10,16 @@ describe("Module: Cell", () => {
expect(
doc.getTextDimensions(doc.splitTextToSize("Octocat loves jsPDF", 50)).h
).toEqual(71.19999999999999);
expect(doc.getTextDimensions("Octocat loves jsPDF").w).toEqual(144.48000000000002);
expect(doc.getTextDimensions("Octocat loves jsPDF").h).toEqual(16);
expect(
doc.getTextDimensions(doc.splitTextToSize("Octocat loves jsPDF", 150)).w
doc.getTextDimensions("Octocat loves jsPDF", { maxWidth: 150}).w
).toEqual(144.48000000000002);
expect(
doc.getTextDimensions(doc.splitTextToSize("Octocat loves jsPDF", 150)).h
doc.getTextDimensions("Octocat loves jsPDF", { maxWidth: 150 }).h
).toEqual(16);
expect(doc.getTextDimensions("Octocat loves jsPDF").w).toEqual(
144.48000000000002
);
expect(doc.getTextDimensions("Octocat loves jsPDF").h).toEqual(16);
expect(doc.getTextDimensions("Octocat loves jsPDF", {maxWidth: 100 }).h).toEqual(34.4);
expect(doc.getTextDimensions("Octocat loves jsPDF", {maxWidth: 100 }).w).toEqual(96.64000000000001);
expect(doc.getTextDimensions("").w).toEqual(0);
expect(doc.getTextDimensions("").h).toEqual(0);
expect(doc.getTextDimensions([""]).w).toEqual(0);
Expand Down