Lightweight embeddable document viewer
npm install vwr.jsA lightweight, embeddable JavaScript library for rendering documents from URLs directly in the browser. Supports multiple document formats through a plugin architecture with a minimal, self-contained UI that requires no external CSS.
This library is currently in early alpha phase and was created with significant AI assistance to solve a specific problem.
- Status: Early alpha - needs improvement and full review
- AI-Assisted Development: This library was built with AI assistance and requires thorough review
- Production Use: Not recommended for production use without thorough testing and review
- Contributions: Feedback, bug reports, and contributions are especially welcome during this alpha phase
- Future Plans: Active development planned to improve stability, performance, and features
This library was built to address a specific document viewing need and will be improved over time. Please use with caution and report any issues you encounter.
- Multiple Formats: PDF, Images (PNG, JPG, GIF, WebP, BMP, ICO), SVG, DOCX, Markdown, CSV, Plain Text
- Zero Dependencies: No external CSS required - all styles are injected automatically
- Zoom Controls: Zoom in/out with toolbar buttons, mouse wheel, or pinch gestures
- Pagination: Multi-page PDF support with page navigation
- Download: Built-in download button for original files
- Fullscreen: Fullscreen mode support (when available)
- TypeScript: Full TypeScript support with type definitions
- Single Bundle: All dependencies bundled - just include one file
``bash`
npm install vwr.js
`javascript`
import { render } from 'vwr.js';
`html
`
You can import using either default or named imports:
`javascript
// Default import (recommended)
import vwr from 'vwr.js';
const container = document.getElementById('viewer');
const viewer = vwr.render(container, 'https://example.com/document.pdf');
`
`javascript
// Named imports
import { render } from 'vwr.js';
const container = document.getElementById('viewer');
const viewer = render(container, 'https://example.com/document.pdf');
`
`javascript
import { render } from 'vwr.js';
const container = document.getElementById('viewer');
const viewer = render(container, 'https://example.com/document.pdf', {
onLoad: (event) => {
console.log('Document loaded:', event);
console.log('Format:', event.mimeType);
console.log('Renderer:', event.renderer);
if (event.pageCount) {
console.log('Pages:', event.pageCount);
}
},
onError: (error) => {
console.error('Error loading document:', error.message);
console.error('Error code:', error.code);
},
onPageChange: (currentPage, totalPages) => {
console.log(Page ${currentPage} of ${totalPages});Zoom: ${zoomLevel * 100}%
},
onZoomChange: (zoomLevel) => {
console.log();
}
});
// Clean up when done
// viewer.destroy();
`
Renders a document from a URL into the specified container element.
#### Parameters
- element (HTMLElement, required): Container element to render the viewer intourl
- (string, required): URL of the document to loadoptions
- (VwrOptions, optional): Configuration options
#### Returns
Returns a VwrInstance object with a destroy() method for cleanup.
`typescript`
interface VwrOptions {
onLoad?: (event: LoadEvent) => void;
onError?: (error: ErrorEvent) => void;
onPageChange?: (currentPage: number, totalPages: number) => void;
onZoomChange?: (zoomLevel: number) => void;
}
#### onLoad
Called when the document is successfully loaded.
`typescript`
interface LoadEvent {
url: string;
mimeType: string;
renderer: string;
pageCount?: number; // Only for paginated documents (PDF)
}
#### onError
Called when an error occurs while loading or rendering the document.
`typescript`
interface ErrorEvent {
url: string;
message: string;
code: 'NETWORK_ERROR' | 'CORS_ERROR' | 'UNSUPPORTED_FORMAT' | 'PARSE_ERROR' | 'UNKNOWN';
originalError?: Error;
}
#### onPageChange
Called when the user navigates to a different page (PDF only).
`typescript`
onPageChange: (currentPage: number, totalPages: number) => void
#### onZoomChange
Called when the zoom level changes.
`typescript`
onZoomChange: (zoomLevel: number) => void
// zoomLevel is a number between 0.25 and 4.0 (25% to 400%)
#### destroy()
Removes the viewer and cleans up all resources.
`javascript`
const viewer = render(container, url);
// ... later
viewer.destroy();
| Format | Extensions | Features |
|--------|------------|----------|
| PDF | .pdf | Pagination, zoom, page navigation |.png
| Images | , .jpg, .jpeg, .gif, .webp, .bmp, .ico | Zoom, pan when zoomed |.svg
| SVG | | Vector scaling, sanitized for security |.docx
| Word Documents | | Formatted HTML output |.md
| Markdown | , .markdown | GitHub Flavored Markdown support |.csv
| CSV | | Table view with header row (max 1000 rows) |.txt
| Plain Text | | Monospace formatting |
`javascript
// PDF
render(container, 'https://example.com/document.pdf');
// Image
render(container, 'https://example.com/image.png');
// SVG
render(container, 'https://example.com/diagram.svg');
// DOCX
render(container, 'https://example.com/document.docx');
// Markdown
render(container, 'https://example.com/README.md');
// CSV
render(container, 'https://example.com/data.csv');
// Plain Text
render(container, 'https://example.com/notes.txt');
`
`javascript`
render(container, url, {
onError: (error) => {
switch (error.code) {
case 'NETWORK_ERROR':
alert('Unable to load document. Please check your connection.');
break;
case 'CORS_ERROR':
alert('Unable to load document due to security restrictions.');
break;
case 'UNSUPPORTED_FORMAT':
alert('This document format is not supported.');
break;
case 'PARSE_ERROR':
alert('Unable to read this document. The file may be corrupted.');
break;
default:
alert('An unexpected error occurred.');
}
}
});
`javascriptPage ${currentPage} of ${totalPages}
render(container, 'https://example.com/document.pdf', {
onPageChange: (currentPage, totalPages) => {
// Update your UI with page information
document.getElementById('page-info').textContent =
;`
}
});
`javascript
const container = document.getElementById('viewer');
let currentViewer = null;
function loadDocument(url) {
// Clean up previous viewer
if (currentViewer) {
currentViewer.destroy();
}
// Load new document
currentViewer = render(container, url, {
onLoad: (event) => {
console.log('Loaded:', event.renderer);
}
});
}
// Load different documents
loadDocument('https://example.com/doc1.pdf');
// Later...
loadDocument('https://example.com/doc2.docx');
`
`html
Format Detection
The library automatically detects document formats using:
1. MIME type from the HTTP response
Content-Type header (primary)
2. File extension as a fallback when MIME type is ambiguous or missingCommon MIME types:
-
application/pdf → PDF
- image/png, image/jpeg, etc. → Images
- image/svg+xml → SVG
- application/vnd.openxmlformats-officedocument.wordprocessingml.document → DOCX
- text/markdown → Markdown
- text/csv → CSV
- text/plain → Plain Text (or Markdown if .md extension)Browser Support
- Chrome (last 2 versions)
- Firefox (last 2 versions)
- Safari (last 2 versions)
- Edge (last 2 versions)
- iOS Safari (last 2 versions)
- Chrome for Android (last 2 versions)
Note: Fullscreen mode may not be available on all platforms (e.g., iOS Safari on iPhone).
Keyboard and Mouse Controls
$3
- Zoom:
Ctrl/Cmd + Scroll (mouse wheel)
- Zoom: Toolbar buttons (+ / -)
- Pan: Click and drag when zoomed beyond fit-to-width
- Page Navigation: Toolbar buttons (< / >)$3
- Zoom: Pinch to zoom
- Pan: Drag when zoomed beyond fit-to-width
CORS Requirements
When loading documents from a different origin, the server must send appropriate CORS headers:
`
Access-Control-Allow-Origin: *
`Or specify your domain:
`
Access-Control-Allow-Origin: https://yourdomain.com
`If CORS headers are missing, you'll see a
CORS_ERROR in the onError callback.Size
- Minified: ~3.2MB
The library includes PDF.js, mammoth.js, marked, DOMPurify, and PapaParse as bundled dependencies.
Development
`bash
Install dependencies
npm installRun tests
npm testRun tests with coverage
npm run test:coverageBuild
npm run buildLint
npm run lintType check
npm run typecheck
``This library was created with significant AI assistance and is currently in early alpha phase.
- Phase: Early Alpha
- Purpose: Built to solve a specific document viewing problem
- Review Status: Needs full code review and testing
- Production Readiness: Not recommended for production use without thorough testing
This library was developed quickly to address a specific need, and while it includes comprehensive features and test coverage, it has not yet undergone:
- Full security audit
- Performance optimization review
- Edge case testing across all supported formats
- Production deployment validation
- Community review and feedback
Active development is planned to:
- Improve stability and error handling
- Optimize performance, especially for large documents
- Add more comprehensive test coverage
- Address edge cases and browser compatibility issues
- Refine the API based on real-world usage
- Complete security review
Contributions, bug reports, and feedback are especially welcome during this alpha phase. Your input will help shape the future of this library.
Please report any issues, suggest improvements, or submit pull requests. All contributions are appreciated!
MIT
Contributions are welcome! Please feel free to submit a Pull Request.