Skip to content

Commit 99927b0

Browse files
UPDATE: textWithLink method to cover multi-line annotated text (#3281)
Co-authored-by: Lukas Holländer <[email protected]>
1 parent 65f4027 commit 99927b0

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed

src/modules/annotations.js

+21-7
Original file line numberDiff line numberDiff line change
@@ -357,21 +357,35 @@ import { jsPDF } from "../jspdf.js";
357357
* @returns {number} width the width of the text/link
358358
*/
359359
jsPDFAPI.textWithLink = function(text, x, y, options) {
360-
var width = this.getTextWidth(text);
361-
var height = this.internal.getLineHeight() / this.internal.scaleFactor;
360+
var totalLineWidth = this.getTextWidth(text);
361+
var lineHeight = this.internal.getLineHeight() / this.internal.scaleFactor;
362+
var linkHeight, linkWidth;
363+
364+
// Checking if maxWidth option is passed to determine lineWidth and number of lines for each line
365+
if (options.maxWidth !== undefined) {
366+
var { maxWidth } = options;
367+
linkWidth = maxWidth;
368+
var numOfLines = this.splitTextToSize(text, linkWidth).length;
369+
linkHeight = Math.ceil(lineHeight * numOfLines);
370+
} else {
371+
linkWidth = totalLineWidth;
372+
linkHeight = lineHeight;
373+
}
374+
362375
this.text(text, x, y, options);
376+
363377
//TODO We really need the text baseline height to do this correctly.
364378
// Or ability to draw text on top, bottom, center, or baseline.
365-
y += height * 0.2;
379+
y += lineHeight * 0.2;
366380
//handle x position based on the align option
367381
if (options.align === "center") {
368-
x = x - width / 2; //since starting from center move the x position by half of text width
382+
x = x - totalLineWidth / 2; //since starting from center move the x position by half of text width
369383
}
370384
if (options.align === "right") {
371-
x = x - width;
385+
x = x - totalLineWidth;
372386
}
373-
this.link(x, y - height, width, height, options);
374-
return width;
387+
this.link(x, y - lineHeight, linkWidth, linkHeight, options);
388+
return totalLineWidth;
375389
};
376390

377391
//TODO move into external library
3.19 KB
Binary file not shown.

test/specs/annotations.spec.js

+12
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,18 @@ describe("Module: Annotations", () => {
7272

7373
comparePdf(doc.output(), "insertLinkAddPage.pdf", "annotations");
7474
});
75+
it("should add a multline link to the page", () => {
76+
var doc = new jsPDF({
77+
floatPrecision: 2
78+
});
79+
80+
doc.textWithLink("This is a very long link text!", 10, 10, {
81+
url: "https://parall.ax/",
82+
maxWidth: 20
83+
});
84+
85+
comparePdf(doc.output(), "multiLineLinkWithText.pdf", "annotations");
86+
});
7587
it("should align text link based on the align option", () => {
7688
var doc = new jsPDF({
7789
unit: "px",

0 commit comments

Comments
 (0)