@epam/pdf-highlighter-kit

中文文档
0.0.22发布于 2026/11/10Apache-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1万

High-performance PDF viewer with intelligent highlighting and text selection capabilities

原始使用文档
文档目录20 节
  1. Installation
  2. Quick Start
  3. Data Model
  4. InputHighlightData
  5. Configuration Options
  6. ViewerOptions
  7. API Reference
  8. Main Methods
  9. Events
  10. Advanced Usage
  11. Page thumbnails
  12. Custom Styling (per highlight)
  13. Theming
  14. Label with icon (e.g. Tabler Icons)
  15. React Integration
  16. Browser Support
  17. Requirements
  18. License
  19. Contributing
  20. Support

PDF Highlight Viewer

High-performance PDF viewer with intelligent highlighting and text selection capabilities for web applications.

npm version License PRs Welcome

An open-source project by BadgerDoc BadgerDoc


Installation

npm install @epam/pdf-highlighter-kit pdfjs-dist

Peer dependency: pdfjs-dist (see Requirements).

Quick Start

import { PDFHighlightViewer } from '@epam/pdf-highlighter-kit';
import type { InputHighlightData } from '@epam/pdf-highlighter-kit';
import '@epam/pdf-highlighter-kit/styles/pdf-highlight-viewer.css';

// Create viewer instance
const viewer = new PDFHighlightViewer();

// Initialize with container element
const container = document.getElementById('pdf-container') as HTMLElement;

await viewer.init(container, {
  enableTextSelection: true,
  enableVirtualScrolling: true,
  bufferPages: 2,
  maxCachedPages: 10,
  interactionMode: 'hybrid',
});

// Load PDF document
await viewer.loadPDF('/path/to/document.pdf');

// Highlights
const highlights: InputHighlightData[] = [
  {
    id: 'term-001',
    bboxes: [
      // page is 1-based
      { page: 1, x1: 100, y1: 200, x2: 300, y2: 220 },
      { page: 3, x1: 80, y1: 140, x2: 260, y2: 160 },
    ],
    style: {
      backgroundColor: '#ffeb3b',
      opacity: 0.3,
      borderColor: '#d4c400',
      borderWidth: '1px',
    },
    label: 'Important Term',
    labelStyle: { fontSize: 11 },
    tooltipText: 'Important Term',
    metadata: {
      frequency: 5,
      tags: ['important', 'glossary'],
    },
  },
];

viewer.loadHighlights(highlights);

// Navigate to a highlight occurrence
viewer.goToHighlight('term-001', 0);

Data Model

InputHighlightData

Each highlight carries its own style. No categories are required.

Labels: You can add an optional label that is displayed to the left of the highlight, flush against it. By default the label uses the highlight’s color (from style.borderColor or style.backgroundColor), border: 1px solid, and padding: 2px 4px. Override any of these with labelStyle (e.g. fontSize, color, padding, border). To hide the label border, set labelStyle: { border: 'none' } (the default border is always applied unless overridden).

Icon before label: Optionally set beforeIcon to an inline SVG string (e.g. from Tabler Icons) to render an icon inside the label frame, to the left of the text. The icon inherits the label color via currentColor. Use labelStyle.iconSize to set the icon size (e.g. 14 or '14px') and labelStyle.iconColor to set the icon color (e.g. '#ff6b6b'); if iconColor is not set, the icon uses the label text color. Only pass trusted SVG content (e.g. from your bundle or @tabler/icons); in React with Vite you can use import iconSvg from '@tabler/icons/icons/outline/alert-circle.svg?raw' and pass iconSvg as beforeIcon.

Scalable label: Set isLabelScalable: true on the highlight so the label’s size (font, padding, icon, border radius) scales with zoom; the label stays proportional to the highlight. Border and outline thickness are not scaled (they stay fixed like the highlight’s outline). Best used with labelStyle values in px or numbers.

export interface BBox {
  x1: number;
  y1: number;
  x2: number;
  y2: number;
  page: number;
}

export interface BBoxDimensions {
  width: number;
  height: number;
}

export type BBoxOrigin = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';

export type InteractionMode = 'select' | 'highlight' | 'hybrid';

export interface HighlightStyle {
  backgroundColor: string;
  borderColor?: string;
  borderWidth?: string;
  outline?: string;
  opacity?: number;
  hoverOpacity?: number;
  pulseAnimation?: boolean;
}

export interface HighlightLabelStyle {
  fontSize?: string | number;
  opacity?: number;
  color?: string;
  backgroundColor?: string;
  padding?: string;
  borderRadius?: string; // e.g. '2px' or shorthand '2px 2px 0 0'
  fontFamily?: string;
  fontWeight?: string | number;
  border?: string;
  borderColor?: string;
  borderWidth?: string;
  outline?: string;
  whiteSpace?: string;
  iconSize?: string | number; // size for beforeIcon (e.g. 14 or '14px')
  iconColor?: string;
  offsetLeft?: number;
  offsetTop?: number;
  outlineRight?: string;
}

export interface InputHighlightData {
  id: string;
  bboxes: BBox[];
  bboxOrigin?: BBoxOrigin;
  bboxSourceDimensions?: BBoxDimensions;
  style?: HighlightStyle;
  label?: string;
  beforeIcon?: string; // inline SVG string (trusted content only, e.g. Tabler icons)
  isLabelScalable?: boolean; // when true, label size scales with zoom (borders stay fixed)
  labelStyle?: HighlightLabelStyle;
  tooltipText?: string;
  metadata?: Record<string, any>;
}

If bboxSourceDimensions is provided, each bbox coordinate is recalculated against the actual page size:

scaledX = (x / bboxSourceDimensions.width) * actualPageWidth;
scaledY = (y / bboxSourceDimensions.height) * actualPageHeight;

Priority (highest to lowest):

  • highlight.bboxOrigin / highlight.bboxSourceDimensions
  • global viewer options (bboxOrigin, bboxSourceDimensions)

Configuration Options

ViewerOptions

export interface HighlightsConfig {
  enableMultilineHover?: boolean;
  defaultStyle?: HighlightStyle;
}

export interface ViewerOptions {
  // Enable text selection functionality
  enableTextSelection?: boolean;

  // Enable virtual scrolling for better performance
  enableVirtualScrolling?: boolean;

  // Number of pages to buffer above/below viewport
  bufferPages?: number;

  // Maximum number of pages to keep in cache
  maxCachedPages?: number;

  // Interaction mode: 'select' | 'highlight' | 'hybrid'
  interactionMode?: InteractionMode;

  // Performance mode (smaller frame budget)
  performanceMode?: boolean;

  // Enable accessibility helpers
  accessibility?: boolean;

  // Highlight UI config (style is per highlight)
  highlightsConfig?: HighlightsConfig;

  // Coordinate origin for incoming bbox values
  // Default: 'bottom-right'
  bboxOrigin?: BBoxOrigin;

  // Page dimensions for which bbox coordinates were calculated
  bboxSourceDimensions?: BBoxDimensions;

  // Only show these document page numbers (1-based). If empty or omitted, all pages are shown.
  selectedPages?: number[];
}

Displaying only selected pages: Use selectedPages to show a subset of the document (e.g. [1, 3, 5] or [2, 4, 6, 8]). The full PDF is still loaded; only the listed pages get DOM containers and participate in scrolling and rendering. Page numbers in the API (e.g. setPage, events, highlights) remain physical document page numbers. You can pass selectedPages in init options or per load via loadPDF(source, { selectedPages }); the latter overrides the init value for that load. getTotalPages() returns the length of the displayed list when selectedPages is set.

API Reference

Main Methods

init(container: HTMLElement, config?: ViewerOptions): Promise<void>

Initialize the viewer with a container element and optional configuration.

loadPDF(source: string | ArrayBuffer | Blob, options?: LoadPDFOptions): Promise<void>

Load a PDF document from URL or ArrayBuffer. Optional second argument:

interface LoadPDFOptions {
  /** Only show these document page numbers (1-based). If empty or omitted, all pages are shown. */
  selectedPages?: number[];
}

Example: await viewer.loadPDF(url, { selectedPages: [1, 3, 5] }); shows only pages 1, 3, and 5. When options.selectedPages is provided, it overrides ViewerOptions.selectedPages for this load.

loadHighlights(highlights: InputHighlightData[]): void

Replace current highlights with the provided list.

addHighlight(highlight: InputHighlightData): void

Add a single highlight (incremental update).

removeHighlight(termId: string): void

Remove highlight by its id.

updateHighlightStyle(termId: string, stylePatch: Partial<HighlightStyle>, labelStylePatch?: Partial<HighlightLabelStyle>): void

Update highlight style by id (patch merge). Optionally pass labelStylePatch to update label styles as well.

goToHighlight(termId: string, occurrenceIndex?: number): void

Navigate to a specific highlight occurrence. occurrenceIndex defaults to 0.

nextHighlight(): void / previousHighlight(): void

Navigate across all highlight occurrences in document order.

setPage(pageNumber: number): void

Navigate to a specific page (1-based).

zoomIn(): void / zoomOut(): void

Zoom in or out of the PDF while preserving the reading position. After navigation to a page, highlight, or coordinate, that target stays at the same viewport position during zoom, even when a neighboring page occupies more of the viewport. The same page and PDF-space position stay anchored across successive zoom changes, including when adjacent pages become more visible at a smaller scale. Scrolling or explicit page navigation establishes a new anchor. Page detection uses actual page bounds, including for documents with mixed page sizes. Zoom commits page sizes and scrolling together; the previous page image remains scaled on screen until the new raster is ready, without changing page height for loading indicators.

setZoom(value: ZoomMode | number): void

Set a specific zoom level (e.g., 1.0 for 100%, 1.5 for 150%). The reading position is preserved as with zoomIn() and zoomOut().

getThumbnails(pageNumbers: number[], options?: ThumbnailOptions): Promise<Map<number, HTMLCanvasElement>>

Render page thumbnails (miniatures) for the given page numbers. Returns a Map of page number → canvas. Use this when you need canvas elements (e.g. for drawing or custom display). Options: maxWidth (target width in px), scale (viewport scale).

getThumbnailsDataUrl(pageNumbers: number[], options?: ThumbnailOptions): Promise<Map<number, string>>

Same as getThumbnails but returns data URLs (e.g. for <img src="...">). Options include maxWidth, scale, format ('image/jpeg' | 'image/webp' | 'image/png'), and quality (0–1 for jpeg/webp). Thumbnails are cached; repeated calls for the same page return cached results.

destroy(): void

Clean up and destroy the viewer instance.

Events

The viewer emits various events that you can listen to:

viewer.addEventListener('initialized', () => {
  console.log('Viewer initialized');
});

viewer.addEventListener('pdfLoaded', (e) => {
  console.log('PDF loaded. Total pages:', e.totalPages);
});

viewer.addEventListener('pageChanged', (e) => {
  console.log('Current page:', e.currentPage);
});

viewer.addEventListener('zoomChanged', (e) => {
  console.log('Zoom changed:', e.scale);
});

viewer.addEventListener('renderComplete', (e) => {
  console.log('Page rendered:', e.pageNumber);
});

viewer.addEventListener('renderError', (e) => {
  console.error('Render error:', e.pageNumber, e.error);
});

viewer.addEventListener('highlightsLoaded', (e) => {
  console.log('Highlights loaded:', e.count);
});

viewer.addEventListener('highlightHover', (e) => {
  console.log('Highlight hover:', e.termId, 'page', e.pageNumber, 'bbox', e.bboxIndex);
});

viewer.addEventListener('highlightBlur', (e) => {
  console.log('Highlight blur:', e.termId);
});

viewer.addEventListener('highlightClick', (e) => {
  console.log('Highlight clicked:', e.termId, 'page', e.pageNumber, 'bbox', e.bboxIndex);
});

viewer.addEventListener('navigationComplete', (e) => {
  console.log('Navigation complete:', e.termId, e.pageNumber, e.occurrenceIndex);
});

viewer.addEventListener('selectionChanged', (e) => {
  console.log('Text selected:', e.text);
  console.log('Pages:', e.pageNumbers);
  console.log('Overlapping highlights:', e.highlights); // array of bbox refs
});

viewer.addEventListener('selectionHighlighted', (e) => {
  console.log('Selection highlighted:', e.termId);
});

viewer.addEventListener('error', (e) => {
  console.error('Viewer error:', e);
});

Event payload fields may include termId, pageNumber, bboxIndex, and bbox depending on event type.

Advanced Usage

Page thumbnails

// ThumbnailOptions: maxWidth?, scale?, format?, quality?
const pageNumbers = Array.from({ length: viewer.getTotalPages() }, (_, i) => i + 1);

// Option 1: get data URLs for <img src="...">
const dataUrls = await viewer.getThumbnailsDataUrl(pageNumbers, {
  maxWidth: 120,
  format: 'image/webp',
  quality: 0.85,
});
// dataUrls is Map<number, string> — use dataUrls.get(pageNum) in img src

// Option 2: get canvases for custom rendering
const canvases = await viewer.getThumbnails(pageNumbers, { maxWidth: 120 });
// canvases is Map<number, HTMLCanvasElement>

For a single page, pass an array with one number: getThumbnailsDataUrl([5], options). Thumbnails are cached inside the viewer; reopening the panel does not re-render unless the cache was cleared (e.g. after loading a new PDF).

Custom Styling (per highlight)

const highlight: InputHighlightData = {
  id: 'note-001',
  bboxes: [{ page: 2, x1: 120, y1: 330, x2: 420, y2: 355 }],
  style: {
    backgroundColor: '#ffd54f',
    opacity: 0.25,
    borderColor: '#ff8f00',
    borderWidth: '1px',
    hoverOpacity: 0.6,
  },
  label: 'My note',
  labelStyle: { padding: '2px 6px', borderRadius: '4px' },
  tooltipText: 'My note',
};

viewer.addHighlight(highlight);

Theming

The viewer's colors follow the DIAL chat palette. Each color is a --phk-* CSS variable that reads the matching DIAL theme variable (--bg-layer-base, --text-primary, --stroke-accent, …). Inside a DIAL app the viewer therefore follows the active theme, dark included; elsewhere it uses the DIAL light palette.

To restyle the viewer, override any --phk-* variable:

.pdf-highlight-viewer,
.pdf-context-menu,
.pdf-tooltip {
  --phk-bg: #ffffff;
  --phk-accent: #0f766e;
  --phk-yellow: #facc15; /* protein highlights and search results */
}

The full list is at the top of styles/pdf-highlight-viewer.css.

Label with icon (e.g. Tabler Icons)

Pass an inline SVG string as beforeIcon to show an icon inside the label frame. Use trusted content only. With Vite you can import SVG as raw string:

// Inline SVG string (e.g. from Tabler: import icon from '@tabler/icons/icons/outline/alert-circle.svg?raw')
const alertIconSvg =
  '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 8v4"/><path d="M12 16h.01"/><circle cx="12" cy="12" r="10"/></svg>';

const highlight: InputHighlightData = {
  id: 'alert-001',
  bboxes: [{ page: 1, x1: 100, y1: 200, x2: 300, y2: 220 }],
  style: { backgroundColor: '#ffeb3b', opacity: 0.3, borderColor: '#d4c400' },
  label: 'Important',
  beforeIcon: alertIconSvg,
  labelStyle: { fontSize: 11, iconSize: 14 },
  tooltipText: 'Important',
};

viewer.addHighlight(highlight);

React Integration

import { useEffect, useRef } from 'react';
import { PDFHighlightViewer } from '@epam/pdf-highlighter-kit';
import type { InputHighlightData } from '@epam/pdf-highlighter-kit';
import '@epam/pdf-highlighter-kit/styles/pdf-highlight-viewer.css';

export function PDFViewer({
  pdfUrl,
  highlights,
}: {
  pdfUrl: string;
  highlights: InputHighlightData[];
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const viewerRef = useRef<PDFHighlightViewer | null>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    const viewer = new PDFHighlightViewer();
    viewerRef.current = viewer;

    (async () => {
      await viewer.init(containerRef.current!, {
        enableTextSelection: true,
        enableVirtualScrolling: true,
      });
      await viewer.loadPDF(pdfUrl);
      viewer.loadHighlights(highlights);
    })();

    return () => {
      viewer.destroy();
      viewerRef.current = null;
    };
  }, [pdfUrl]);

  useEffect(() => {
    viewerRef.current?.loadHighlights(highlights);
  }, [highlights]);

  return <div ref={containerRef} style={{ width: '100%', height: '100vh' }} />;
}

Browser Support

  • Chrome/Edge (latest 2 versions)
  • Firefox (latest 2 versions)
  • Safari (latest 2 versions)

Requirements

  • pdfjs-dist: ^5.4.149 || ^6.0.0 (peer dependency)

License

Apache-2.0

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and questions, please use the GitHub Issues page.

版本与发布记录

@epam/pdf-highlighter-kit 共发布 18 个版本,首次发布于 2025/12/17;过去 12 个月发布了 18 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.0.22latest2026/11/103 天前
0.0.212026/11/058 天前
0.0.202026/11/049 天前
0.0.192026/09/112 个月前
0.0.182026/06/174 个月前
0.0.172026/06/164 个月前

关于 @epam/pdf-highlighter-kit 的常见问题

@epam/pdf-highlighter-kit 是什么?

High-performance PDF viewer with intelligent highlighting and text selection capabilities

如何安装 @epam/pdf-highlighter-kit?

在项目目录运行 npm install @epam/pdf-highlighter-kit,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:pdfjs-dist(^5.4.149 || ^6.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@epam/pdf-highlighter-kit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@epam/pdf-highlighter-kit 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@epam/pdf-highlighter-kit 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@epam/pdf-highlighter-kit 可以商用吗?

@epam/pdf-highlighter-kit 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@epam/pdf-highlighter-kit 的下载量有多少?

根据 npm 官方下载统计,@epam/pdf-highlighter-kit 在 2026/10/14 – 2026/11/12 这 30 天内被下载 10,308 次,日均约 344 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@epam/pdf-highlighter-kit 还在维护吗?

最新版本 0.0.22 发布于 2026/11/10(3 天前);至今共发布 18 个版本,其中过去 12 个月发布了 18 个;首次发布于 2025/12/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。