By default, the texts in page which are not actually hyperlinks, they will not be rendered as links.
For example,
https://google.fr is treated as a normal text.
In this example, we will create a plugin to find all the links and turn them into real hyperlinks.
Create a plugin
Like any
built in plugin, a custom plugin is actually a function that returns an instance of core
`Plugin`
.
Our plugin called `findLinksPlugin`
does not need any options, so it looks like following:
import { Plugin } from '@react-pdf-viewer/core';
const findLinksPlugin = (): Plugin => {
return {
...
};
};
`Plugin`
allows you to perform additional action when a particular event happens. For this specific example, we will hook on the `onTextLayerRender`
event which is triggered when all text in each page is rendered completely.
import { PluginOnTextLayerRender } from '@react-pdf-viewer/core';
const findLinksPlugin = (): Plugin => {
const findLinks = (e: PluginOnTextLayerRender) => {
...
}
return {
onTextLayerRender: findLinks,
};
};
Within the `findLinks`
function, we will replace all the link-like text with hyperlinks. There are some libraries to do that such as
We will use the
linkifyjs library, so ensure that the following package is installed:
If you use Typescript, then install the type definitions for `linkifyjs`
:
$ npm install --save-dev @types/linkifyjs
Find and replace links
It is easy to query all text elements in each page and use the
linkifyjs libary to find links:
import linkifyElement from 'linkifyjs/element';
const findLinks = (e: PluginOnTextLayerRender) => {
e.ele
.querySelectorAll('.rpv-core-text')
.forEach((textEle) => {
linkifyElement(textEle as HTMLElement, {
attributes: {
style: 'color: transparent; text-decoration: none;',
target: '_blank',
},
});
});
};
You can customize the attributes of each link by passing them to the `attributes`
parameter.
See also