How to Highlight Text in PDFs Programmatically with JavaScript
Annotations are a fundamental part of the document experience. Whether your users are reviewing a legal contract or grading an assignment, they need to highlight key phrases and leave feedback.
In this tutorial, we'll explore two ways to add highlight annotations programmatically: using the open-source PDF.js library and using the Aoexl SDK.
1. Using PDF.js (Open Source)
PDF.js is a powerful viewer, but it wasn't built for persistent document editing. To show highlights, you typically have to "simulate" them by rendering HTML overlays on top of the PDF canvas.
The Problem with PDF.js Highlights
- Not Persistent: Highlights exist only in your app's UI state, not inside the PDF file.
- Coordination: You have to manually map coordinates from the PDF page to your HTML overlay.
- Complexity: Handling zoom and rotation requires significant math to keep the highlights aligned.
Basic approach
You can retrieve existing annotations using getAnnotations(), but creating new ones that save back to the PDF is not supported out of the box.

2. Using the Aoexl SDK (Commercial)
The Aoexl SDK treats annotations as first-class citizens. When you add a highlight via the SDK, it's a real PDF object that can be saved, flattened, or exported to other viewers.
Setup
Install the viewer package:
npm install @aoexl/viewerProgrammatic Highlighting
The Aoexl SDK provides a simple constructor for HighlightAnnotation. You define the page index and the rectangles you want to highlight.
import { AoexlViewer } from '@aoexl/viewer';
const instance = await AoexlViewer.load({
container: "#viewer",
document: "document.pdf"
});
// Define the region to highlight
const rects = [
new AoexlViewer.Geometry.Rect({
left: 50, top: 100, width: 200, height: 20
})
];
const annotation = new AoexlViewer.Annotations.HighlightAnnotation({
pageIndex: 0,
rects: rects,
color: new AoexlViewer.Color({ r: 255, g: 255, b: 0 }) // Yellow
});
// Persist the annotation
await instance.create(annotation);
console.log("Highlight added successfully.");Why use Aoexl for Annotations?
- Persistence: Annotations are embedded in the PDF and follow the document everywhere.
- Automatic Scaling: The SDK handles zoom, rotation, and coordinate mapping automatically.
- Rich Interaction: Users can click, move, or delete programmatically added highlights if given permission.
- Flattening: Easily "burn" highlights into the PDF for permanent record-keeping.
Conclusion
If you only need to show temporary, non-interactive highlights for a specific session, PDF.js can be made to work with custom CSS overlays. However, if your application requires real document markup that stakeholders can see in standard PDF readers (like Acrobat), the Aoexl SDK provides the only production-grade solution.