npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

universal-doc-viewer

v1.0.4

Published

Framework bağımsız çoklu doküman görüntüleme çözümü

Downloads

22

Readme

Universal Document Viewer (UDV)

A free, lightweight and framework-independent document viewing solution. It can be used to view PDF, Word, Excel and image files in any web project.

Features

  • Multi-Format Support: PDF, DOCX, DOC, XLS, XLSX, CSV, JPG, JPEG, PNG, GIF, BMP, WEBP, SVG
  • Framework Independent: Can be used in any JavaScript project (compatible with React, Angular, Vue, etc.)
  • Responsive Design: Compatible with all screen sizes including mobile
  • Lightweight: Minimal dependencies, high performance
  • Advanced Features: Zoom, pagination, rotation, dark mode
  • Fully Customizable: Can be customized according to your needs
  • Compatible with Modern Browsers: Chrome, Firefox, Safari, Edge

Installation

Installation with NPM:

npm install universal-doc-viewer

or via CDN:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/universal-doc-viewer@latest/dist/universal-doc-viewer.min.css">
<script src="https://cdn.jsdelivr.net/npm/universal-doc-viewer@latest/dist/universal-doc-viewer.min.js"></script>

Usage

Basic Usage

<div id="viewer" style="width: 100%; height: 500px;"></div>

<script>
  // Initialize the viewer
  const viewer = new UniversalDocViewer({
    container: 'viewer',
    toolbar: {
      enabled: true
    }
  });
  
  // Load a document (can be URL, File or Blob)
  viewer.loadDocument('path/to/document.pdf');
  
  // or from a file input
  const fileInput = document.getElementById('file-input');
  fileInput.addEventListener('change', (e) => {
    if (e.target.files.length > 0) {
      viewer.loadDocument(e.target.files[0]);
    }
  });
</script>

Options

const viewer = new UniversalDocViewer({
  // Required: Viewer container (ID string or HTML element)
  container: 'viewer',
  
  // Optional: Toolbar configuration
  toolbar: {
    enabled: true // Enable/disable toolbar
  },
  
  // Optional: Custom adapters
  adapters: {
    // Custom adapters here
  },
  
  // Optional: Event listeners
  onDocumentLoaded: (result) => {
    console.log('Document loaded:', result);
  },
  onError: (error) => {
    console.error('Error:', error);
  }
});

Adapters Structure

Universal Document Viewer has a modular architecture and uses separate adapters for each file type. You can extend the supported formats by adding your own adapters.

// Example of a custom adapter
class CustomFormatAdapter extends BaseViewerAdapter {
  // Adapter implementation details
}

// Add the custom adapter to the viewer
const viewer = new UniversalDocViewer({
  container: 'viewer',
  adapters: {
    'custom': new CustomFormatAdapter()
  }
});

// Use it by specifying the custom type
viewer.loadDocument('path/to/file.xyz', { type: 'custom' });

Framework Integrations

React

import React, { useEffect, useRef } from 'react';
import { UniversalDocViewer } from 'universal-doc-viewer';

function DocumentViewer({ documentUrl }) {
  const containerRef = useRef(null);
  const viewerRef = useRef(null);
  
  useEffect(() => {
    if (containerRef.current && !viewerRef.current) {
      // Initialize the viewer
      viewerRef.current = new UniversalDocViewer({
        container: containerRef.current
      });
    }
    
    // Load document
    if (viewerRef.current && documentUrl) {
      viewerRef.current.loadDocument(documentUrl);
    }
    
    // Cleanup
    return () => {
      if (viewerRef.current) {
        viewerRef.current.destroy();
        viewerRef.current = null;
      }
    };
  }, [documentUrl]);
  
  return <div ref={containerRef} style={{ width: '100%', height: '500px' }} />;
}

export default DocumentViewer;

Vue.js

<template>
  <div ref="viewerContainer" style="width: 100%; height: 500px;"></div>
</template>

<script>
import { UniversalDocViewer } from 'universal-doc-viewer';

export default {
  name: 'DocumentViewer',
  props: {
    documentUrl: String
  },
  data() {
    return {
      viewer: null
    };
  },
  mounted() {
    // Initialize viewer
    this.viewer = new UniversalDocViewer({
      container: this.$refs.viewerContainer
    });
    
    // Load document
    if (this.documentUrl) {
      this.viewer.loadDocument(this.documentUrl);
    }
  },
  watch: {
    documentUrl(newUrl) {
      if (this.viewer && newUrl) {
        this.viewer.loadDocument(newUrl);
      }
    }
  },
  beforeDestroy() {
    // Cleanup
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  }
};
</script>

Angular

import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { UniversalDocViewer } from 'universal-doc-viewer';

@Component({
  selector: 'app-document-viewer',
  template: `
    <div #viewerContainer style="width: 100%; height: 500px;"></div>
  `
})
export class DocumentViewerComponent implements OnInit, OnDestroy {
  @ViewChild('viewerContainer', { static: true }) viewerContainer: ElementRef;
  @Input() documentUrl: string;
  
  private viewer: any;
  
  ngOnInit() {
    // Initialize viewer
    this.viewer = new UniversalDocViewer({
      container: this.viewerContainer.nativeElement
    });
    
    // Load document
    if (this.documentUrl) {
      this.viewer.loadDocument(this.documentUrl);
    }
  }
  
  ngOnChanges(changes) {
    if (changes.documentUrl && this.viewer && this.documentUrl) {
      this.viewer.loadDocument(this.documentUrl);
    }
  }
  
  ngOnDestroy() {
    // Cleanup
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  }
}

API Reference

UniversalDocViewer

class UniversalDocViewer {
  constructor(options: ViewerOptions);
  loadDocument(document: string | File | Blob, options?: LoadOptions): Promise<any>;
  destroy(): void;
}

interface ViewerOptions {
  container: string | HTMLElement;
  toolbar?: {
    enabled?: boolean;
  };
  adapters?: Record<string, BaseViewerAdapter>;
  onDocumentLoaded?: (result: any) => void;
  onError?: (error: Error) => void;
}

interface LoadOptions {
  type?: string;
  filename?: string;
  viewerOptions?: Record<string, any>;
}

ViewerAdapter API

class BaseViewerAdapter {
  constructor(options?: AdapterOptions);
  loadDocument(document: string | File | Blob, options?: any): Promise<any>;
  supportsMultiplePages(): boolean;
  supportsZoom(): boolean;
  supportsDownload(): boolean;
  getPageInfo(): { currentPage: number, totalPages: number };
  nextPage(): Promise<void>;
  prevPage(): Promise<void>;
  goToPage(pageNumber: number): Promise<void>;
  zoomIn(factor?: number): Promise<void>;
  zoomOut(factor?: number): Promise<void>;
  setZoom(level: number): Promise<void>;
  download(documentInfo: any): void;
  destroy(): void;
}

Development

Requirements

  • Node.js (>=14.x)
  • npm or yarn

Project Structure

The project structure is as follows:

universal-doc-viewer/
├── src/
│   ├── js/                 # Main JavaScript source files
│   │   ├── adapters/       # Adapters for different document types
│   │   └── UniversalDocViewer.js  # Main viewer class
│   ├── css/                # CSS style files
│   └── index.js            # Library entry point
├── dist/                   # Compiled files
├── examples/               # Usage examples
└── webpack.config.js       # Webpack configuration

Note: This project originally had two UniversalDocViewer.js files (src/UniversalDocViewer.js and src/js/UniversalDocViewer.js). For project cleanup and to avoid confusion, src/js/UniversalDocViewer.js was kept and the other file was removed. If you notice any loss of functionality after this cleanup, please contact us.

Project Setup

# Clone the repository
git clone https://github.com/username/universal-doc-viewer.git
cd universal-doc-viewer

# Install dependencies
npm install

# Start development server
npm run start

# Build for production
npm run build

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE file for more information.

Contact

API Integration for Document Viewing

Universal Document Viewer supports viewing documents with reference IDs through API integration. This feature allows you to view documents stored in databases by making API calls.

Viewing Documents with ReferenceId

The viewer can display documents in two ways:

  1. Base64 String: By directly providing the document content in base64 format
  2. ReferenceId: By retrieving the document content in base64 format from an API using a document reference ID

API Integration Example

// Create viewer and configure API settings
const viewer = new UniversalDocViewer('viewer-container', {
  apiUrl: 'https://api.example.com/documents/{referenceId}',
  apiMethod: 'GET',
  apiConfig: {
    headers: { 
      'Content-Type': 'application/json',
      'Authorization': 'Bearer your-token-here'
    },
    responseDataPath: 'data.base64Content',
    withCredentials: true
  }
});

// Load document with referenceId as a string
viewer.loadDocument('doc-123456');

// Load document with referenceId as an object
viewer.loadDocument({
  referenceId: 'doc-789012',
  type: 'pdf'
});

API Configuration Options

{
  apiUrl: 'https://api.example.com/documents/{referenceId}', // {referenceId} will be replaced with the actual ID
  apiMethod: 'GET', // or 'POST'
  apiHeaders: { 
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token'
  },
  apiQueryParams: {
    extraParam: 'value',
    referenceType: 'document'
  },
  apiBodyParams: {
    // Body parameters for POST method
    extraData: 'value'
  },
  apiConfig: {
    responseDataPath: 'data.document.base64Content', // Path to base64 content in API response
    referenceIdQueryParam: 'docId', // Name of the referenceId field to be sent as query param
    referenceIdBodyParam: 'documentId', // Name of the referenceId field to be sent in body
    withCredentials: true // withCredentials for CORS
  }
}

API Response Format

The response from the API should be in the following format:

{
  "status": "success",
  "data": {
    "base64Content": "data:application/pdf;base64,JVBERi0xLjcKJeLj..."
  }
}

or

{
  "data": {
    "document": {
      "base64Content": "data:application/pdf;base64,JVBERi0xLjcKJeLj..."
    }
  }
}

In this case, the responseDataPath parameter should be data.base64Content or data.document.base64Content accordingly.