Files
docx-js/docs/usage/hyperlinks.md
Thomas Gerbet 3f257bf5a4 Add the pageref element
This instruction is useful if you want to get the number of the page
containing a specific bookmark.
2021-08-03 21:17:32 +02:00

1.8 KiB

Hyperlinks

There are two types of hyperlinks: internal (pointing to a bookmark inside the document) and external (pointing to an external url).

Internal

To create an internal hyperlink you need first to create a bookmark (the paragraph that will be the destination of the hyperlink) with doc.createBookmark(anchor, text).

A bookmark is composed of an anchor (an identifier) and the text displayed. After creating a bookmark just add it to a paragraph with paragraph.addBookmark(bookmark)

For example:

const paragraph = this.doc.createParagraph();
const bookmark = this.doc.createBookmark('anchorForChapter1', 'This is chapter1');
paragraph.addBookmark(bookmark);

Then you can create an hyperlink pointing to that bookmark with doc.createInternalHyperLink(anchor,text):

const paragraph = this.doc.createParagraph();
const link = this.doc.createInternalHyperLink('anchorForChapter1', 'This is a link to chapter1');
paragraph.addHyperLink(link);

You can also get the page number of the bookmark by creating a page reference to it:

new Paragraph({
    children: [
        new TextRun("The chapter1 can be seen on page "),
        new PageRef("anchorForChapter1"),
    ]
})

External

To create an external hyperlink you just need to specify the url and the text of the link, then add it to a paragraph with doc.createHyperlink(url, text):

const paragraph = this.doc.createParagraph();
const link = this.doc.createHyperlink('https://docx.js.org', 'This is an external link');
paragraph.addHyperLink(link);

It is possible to set the style of the text of an hyperlink. This can be done applying run formatting on TextRun property of the hyperlink.

Example:

const link = this.doc.createHyperlink('https://docx.js.org', 'This is an external link');
link.TextRun.bold().italics()