React PDF viewer
v1.7.0

Example: Find and replace links found in each page with hyperlinks

In this example, we will learn how to find all links in the plain text of each page, and turn them into hyperlinks. There're some external libraries to do that. This example will use linkifyjs.

Install linkifyjs

Run the following commands to instance the linkifyjs package:

npm install linkifyjs

If you use Typescript, then install the type definitions for linkifyjs:

npm install --save-dev @types/linkifyjs

Find and replace links

We need to handle the onTextLayerRender event which is triggered when the text layer is rendered completely.

Inside the handler, we can access the text wrapper element, and then use the linkifyjs' API to find and replace links.

const onTextLayerRender = (e: TextLayerRenderEvent) => {
    // `e.ele` represents the text wrapper element
    
    // Find all text elements
    e.ele.querySelectorAll('.viewer-text').forEach((textEle) => {
        linkifyElement(textEle as HTMLElement, {
            attributes: {
                style: 'color: transparent; text-decoration: none;',
            },
        });
    });
};

<Viewer
    onTextLayerRender={onTextLayerRender}
/>

(The sample code)

/ 1
90%