Skip to content
Highlight with Keywords Programmatically

An image of highlight with Keywords Programmatically

When the PDF document is loaded, the system programmatically highlights three keywords:

  1. Case-insensitive: “compilation technique”
  2. Case-sensitive: “JavaScript”
  3. Whole word with regular expression: “language” or “languages”

The selected keywords should appear more than once and be located across different pages. Each highlighted keyword uses a different color.

The useHighlightContext provides a function to highlight text in a PDF without any manual text selection. This is especially useful for:

  • Emphasizing important terms or key concepts
  • Displaying search results directly in the document
  • Highlighting specific patterns or keywords dynamically (e.g., from an API or data set)

Here are the functions we’re using for this example

NameObjective
highlightSet initial highlight text once the document is loaded
clearClear all highlight text
import {
RPConfig,
RPProvider,
RPDefaultLayout,
RPPages,
useHighlightContext,
} from "@pdf-viewer/react";
import React, { useEffect } from "react";
const HighlightWords = () => {
const { highlight, clear } = useHighlightContext();
useEffect(() => {
highlight([
{
// This matches the word "compilation technique" in a case-insensitive manner
keyword: "compilation technique",
highlightColor: "rgba(255, 179, 0, 0.5)",
},
{
// This matches the word "JavaScript" in a case-sensitive manner
keyword: "JavaScript",
highlightColor: "rgba(0, 255, 0, 0.5)",
options: { matchCase: true, wholeWords: true },
},
{
// This regular expression matches the word "language" or "languages"
keyword: /\blanguage(s)?\b/,
highlightColor: "rgba(255, 0, 255, 0.5)",
}
]);
}, []);
return <button onClick={clear}> Clear highlight </button>;
};
export const AppPdfViewer = () => {
return (
<>
<RPConfig licenseKey="YOUR_LICENSE_KEY">
<RPProvider src="https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf">
<HighlightWords />
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
</RPConfig>
</>
);
};