Find and replace links found in each page

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:
$ npm install linkifyjs
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` represents the element containing all text elements in each page
// Find all text elements
e.ele
// `rpv-core-text` is the CSS class of each text element
.querySelectorAll('.rpv-core-text')
.forEach((textEle) => {
linkifyElement(textEle as HTMLElement, {
attributes: {
// Custom styles
style: 'color: transparent; text-decoration: none;',
// Open link in new tab
target: '_blank',
},
});
});
};
You can customize the attributes of each link by passing them to the attributes parameter.