universal-doc-viewer
v1.0.4
Published
Framework bağımsız çoklu doküman görüntüleme çözümü
Downloads
22
Maintainers
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-vieweror 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 configurationNote: 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 buildContributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
Distributed under the MIT License. See LICENSE file for more information.
Contact
- Email: [email protected]
- GitHub: github.com/username/universal-doc-viewer
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:
- Base64 String: By directly providing the document content in base64 format
- 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.
