You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

@nyazkhan/react-pdf-viewer

Package Overview
Dependencies
Maintainers
0
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nyazkhan/react-pdf-viewer

A comprehensive React TypeScript component library for viewing and interacting with PDF files using Mozilla PDF.js. Features include text selection, highlighting, search, sidebar, multiple view modes, and complete PDF.js web viewer functionality.

1.1.1
latest
Source
npmnpm
Version published
Maintainers
0
Created
Source

React PDF.js Viewer

npm version License: MIT TypeScript

A comprehensive React TypeScript component library for viewing and interacting with PDF files using Mozilla PDF.js. Features complete PDF.js web viewer functionality with modern React patterns, full TypeScript support, and enhanced user experience.

✨ Features

🔥 Complete PDF.js Web Viewer Functionality

  • 📄 PDF Rendering: High-quality PDF rendering with Mozilla PDF.js
  • 🖍️ Text Highlighting: Search and highlight text across all pages
  • 🔍 Text Selection: Smooth text selection that works perfectly at any zoom level
  • 🔎 Search: Find text with result navigation and highlighting
  • 🗂️ Sidebar: Thumbnails, outline, attachments, and layers
  • 👁️ View Modes: Single page, continuous, two-page, and book views
  • 🔍 Zoom Controls: Fit to page, fit to width, actual size, custom zoom
  • 🛠️ Tools: Hand/pan, text selection, annotation tools
  • ⌨️ Keyboard Shortcuts: All official PDF.js keyboard shortcuts
  • 🎦 Presentation Mode: Full-screen document viewing
  • 🖨️ Print & Download: Complete document export functionality
  • 📱 Responsive Design: Mobile-friendly and responsive layout
  • 🎨 Customizable: Extensive theming and styling options

🚀 Enhanced React Integration

  • TypeScript First: Full type safety and IntelliSense support
  • 🎣 React Hooks: Modern React patterns with hooks and context
  • 🔄 State Management: Comprehensive state management for all viewer features
  • 🛡️ Error Handling: Robust error boundaries and fallback mechanisms
  • 🏗️ Component Architecture: Modular, reusable component design
  • 📦 Tree Shakeable: Import only the components you need

🚀 Installation

npm install @nyazkhan/react-pdf-viewer pdfjs-dist
yarn add @nyazkhan/react-pdf-viewer pdfjs-dist
pnpm add @nyazkhan/react-pdf-viewer pdfjs-dist

📖 Quick Start

Basic Usage

import React from 'react'
import { PDFViewer } from '@nyazkhan/react-pdf-viewer'
import '@nyazkhan/react-pdf-viewer/styles/viewer.css'

function App() {
  return (
    <div style={{ height: '100vh' }}>
      <PDFViewer
        file="/path/to/your/document.pdf"
        width="100%"
        height="100%"
      />
    </div>
  )
}

export default App

Advanced Usage with All Features

import React, { useState } from 'react'
import {
  PDFViewer,
  type PDFDocumentProxy,
  type PDFHighlightType,
  type ViewMode,
  type SidebarView
} from '@nyazkhan/react-pdf-viewer'
import '@nyazkhan/react-pdf-viewer/styles/viewer.css'

function AdvancedPDFViewer() {
  const [highlights, setHighlights] = useState<PDFHighlightType[]>([])
  const [viewMode, setViewMode] = useState<ViewMode>('single')
  const [sidebarView, setSidebarView] = useState<SidebarView>('thumbnails')

  const handleDocumentLoad = (pdf: PDFDocumentProxy) => {
    console.log(`Loaded PDF with ${pdf.numPages} pages`)
  }

  const handleSearch = (term: string) => {
    console.log(`Searching for: ${term}`)
  }

  return (
    <PDFViewer
      file="/sample.pdf"
      highlights={highlights}
      viewMode={viewMode}
      sidebarView={sidebarView}
      enableTextSelection={true}
      enableKeyboardShortcuts={true}
      onDocumentLoad={handleDocumentLoad}
      onViewModeChange={setViewMode}
      onSidebarViewChange={setSidebarView}
      onSearch={handleSearch}
      width="100%"
      height="100vh"
      showPageControls={true}
      showZoomControls={true}
      showSearchOption={true}
      showPrintOption={true}
      showDownloadOption={true}
    />
  )
}

Text Highlighting

import React, { useState, useCallback } from 'react'
import { PDFViewer, type PDFHighlightType, type PDFDocumentProxy } from '@nyazkhan/react-pdf-viewer'

function PDFWithHighlighting() {
  const [highlights, setHighlights] = useState<PDFHighlightType[]>([])
  const [pdfDocument, setPdfDocument] = useState<PDFDocumentProxy | null>(null)

  const createHighlight = useCallback(async (searchText: string) => {
    if (!pdfDocument) return

    const newHighlights: PDFHighlightType[] = []
    
    for (let pageNum = 1; pageNum <= pdfDocument.numPages; pageNum++) {
      const page = await pdfDocument.getPage(pageNum)
      const textContent = await page.getTextContent()
      
      // Your highlighting logic here
      // ... (implementation details)
    }
    
    setHighlights(newHighlights)
  }, [pdfDocument])

  return (
    <div>
      <input
        type="text"
        placeholder="Enter text to highlight"
        onKeyPress={(e) => {
          if (e.key === 'Enter') {
            createHighlight(e.currentTarget.value)
          }
        }}
      />
      <PDFViewer
        file="/document.pdf"
        highlights={highlights}
        onDocumentLoad={setPdfDocument}
        width="100%"
        height="600px"
      />
    </div>
  )
}

🎛️ API Reference

PDFViewer Props

PropTypeDefaultDescription
filestring | File | ArrayBuffer | Uint8Array-Required. PDF file to display
widthstring | number"100%"Viewer width
heightstring | number"600px"Viewer height
pagenumber1Initial page number
scalenumber1.0Initial zoom scale
rotationnumber0Initial rotation (0, 90, 180, 270)
viewModeViewMode"single"Page view mode
sidebarViewSidebarView"none"Sidebar view type
highlightsPDFHighlightType[][]Text highlights to display
enableTextSelectionbooleantrueEnable text selection
enableKeyboardShortcutsbooleantrueEnable keyboard shortcuts
renderToolbarbooleantrueShow toolbar
renderSidebarbooleantrueShow sidebar

Event Handlers

PropTypeDescription
onDocumentLoad(pdf: PDFDocumentProxy) => voidCalled when PDF loads
onPageChange(page: number) => voidCalled when page changes
onScaleChange(scale: number) => voidCalled when zoom changes
onViewModeChange(mode: ViewMode) => voidCalled when view mode changes
onSearch(term: string) => voidCalled when searching
onError(error: Error) => voidCalled on errors

Types

type ViewMode = 'single' | 'continuous' | 'two-page' | 'book'
type SidebarView = 'none' | 'thumbnails' | 'outline' | 'attachments' | 'layers'
type ToolbarTool = 'none' | 'hand' | 'selection' | 'annotation'

interface PDFHighlightType {
  id: string
  pageNumber: number
  rects: PDFRect[]
  color?: string
  opacity?: number
  content?: string
}

interface PDFRect {
  left: number
  top: number
  width: number
  height: number
}

⌨️ Keyboard Shortcuts

ShortcutAction
n, j, SpaceNext page
p, k, Shift+SpacePrevious page
Ctrl/Cmd + +Zoom in
Ctrl/Cmd + -Zoom out
Ctrl/Cmd + 0Actual size
Ctrl/Cmd + FFind/Search
Ctrl/Cmd + GFind next
Ctrl/Cmd + OOpen file
Ctrl/Cmd + SSave/Download
Ctrl/Cmd + PPrint
F4Toggle sidebar
HomeFirst page
EndLast page
rRotate clockwise
Shift + rRotate counter-clockwise

🎨 Styling

Import the default styles:

@import '@nyazkhan/react-pdf-viewer/styles/viewer.css';

Or customize with CSS variables:

.pdf-viewer {
  --pdf-toolbar-bg: #2c3e50;
  --pdf-toolbar-color: white;
  --pdf-sidebar-bg: #34495e;
  --pdf-page-border: #ddd;
  --pdf-highlight-color: #ffff00;
  --pdf-selection-color: #3498db;
}

📱 Browser Support

  • ✅ Chrome 90+
  • ✅ Firefox 88+
  • ✅ Safari 14+
  • ✅ Edge 90+
  • ✅ Mobile browsers (iOS Safari 14+, Chrome Mobile 90+)

🔧 Requirements

  • React: 16.8.0 or higher
  • pdfjs-dist: 3.0.0 or higher
  • Modern browser with ES2017 support

📝 License

MIT © Nyaz Khan

🤝 Contributing

Contributions are welcome! Please see our Contributing Guide for details.

🐛 Issues

Found a bug? Please open an issue with a detailed description.

🌟 Star History

Star History Chart

Made with ❤️ for the React community

Keywords

react

FAQs

Package last updated on 28 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts