Skip to content

Commit

Permalink
UPDATE: textWithLink method to cover multi-line annotated text (#3281)
Browse files Browse the repository at this point in the history
Co-authored-by: Lukas Holländer <[email protected]>
  • Loading branch information
Goku-kun and HackbrettXXX committed Oct 28, 2021
1 parent 65f4027 commit 99927b0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
28 changes: 21 additions & 7 deletions src/modules/annotations.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,21 +357,35 @@ import { jsPDF } from "../jspdf.js";
* @returns {number} width the width of the text/link
*/
jsPDFAPI.textWithLink = function(text, x, y, options) {
var width = this.getTextWidth(text);
var height = this.internal.getLineHeight() / this.internal.scaleFactor;
var totalLineWidth = this.getTextWidth(text);
var lineHeight = this.internal.getLineHeight() / this.internal.scaleFactor;
var linkHeight, linkWidth;

// Checking if maxWidth option is passed to determine lineWidth and number of lines for each line
if (options.maxWidth !== undefined) {
var { maxWidth } = options;
linkWidth = maxWidth;
var numOfLines = this.splitTextToSize(text, linkWidth).length;
linkHeight = Math.ceil(lineHeight * numOfLines);
} else {
linkWidth = totalLineWidth;
linkHeight = lineHeight;
}

this.text(text, x, y, options);

//TODO We really need the text baseline height to do this correctly.
// Or ability to draw text on top, bottom, center, or baseline.
y += height * 0.2;
y += lineHeight * 0.2;
//handle x position based on the align option
if (options.align === "center") {
x = x - width / 2; //since starting from center move the x position by half of text width
x = x - totalLineWidth / 2; //since starting from center move the x position by half of text width
}
if (options.align === "right") {
x = x - width;
x = x - totalLineWidth;
}
this.link(x, y - height, width, height, options);
return width;
this.link(x, y - lineHeight, linkWidth, linkHeight, options);
return totalLineWidth;
};

//TODO move into external library
Expand Down
Binary file added test/reference/multiLineLinkWithText.pdf
Binary file not shown.
12 changes: 12 additions & 0 deletions test/specs/annotations.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ describe("Module: Annotations", () => {

comparePdf(doc.output(), "insertLinkAddPage.pdf", "annotations");
});
it("should add a multline link to the page", () => {
var doc = new jsPDF({
floatPrecision: 2
});

doc.textWithLink("This is a very long link text!", 10, 10, {
url: "https://parall.ax/",
maxWidth: 20
});

comparePdf(doc.output(), "multiLineLinkWithText.pdf", "annotations");
});
it("should align text link based on the align option", () => {
var doc = new jsPDF({
unit: "px",
Expand Down

0 comments on commit 99927b0

Please sign in to comment.