vwr.js
v0.2.2
Published
Lightweight embeddable document viewer
Maintainers
Readme
vwr.js
A 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.
Important Notice
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.
Features
- 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
Installation
npm
npm install vwr.jsES Module
import { render } from 'vwr.js';Quick Start
Basic Usage
<!DOCTYPE html>
<html>
<head>
<title>Document Viewer</title>
</head>
<body>
<div id="viewer"></div>
<script src="vwr.min.js"></script>
<script>
const container = document.getElementById('viewer');
const viewer = vwr.render(container, 'https://example.com/document.pdf');
</script>
</body>
</html>With ES Modules
You can import using either default or named imports:
// Default import (recommended)
import vwr from 'vwr.js';
const container = document.getElementById('viewer');
const viewer = vwr.render(container, 'https://example.com/document.pdf');// Named imports
import { render } from 'vwr.js';
const container = document.getElementById('viewer');
const viewer = render(container, 'https://example.com/document.pdf');With Options and Callbacks
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}`);
},
onZoomChange: (zoomLevel) => {
console.log(`Zoom: ${zoomLevel * 100}%`);
}
});
// Clean up when done
// viewer.destroy();API Reference
render(element, url, options?)
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.
Options
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.
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.
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).
onPageChange: (currentPage: number, totalPages: number) => voidonZoomChange
Called when the zoom level changes.
onZoomChange: (zoomLevel: number) => void
// zoomLevel is a number between 0.25 and 4.0 (25% to 400%)Instance Methods
destroy()
Removes the viewer and cleans up all resources.
const viewer = render(container, url);
// ... later
viewer.destroy();Supported Formats
| Format | Extensions | Features |
|--------|------------|----------|
| PDF | .pdf | Pagination, zoom, page navigation |
| Images | .png, .jpg, .jpeg, .gif, .webp, .bmp, .ico | Zoom, pan when zoomed |
| SVG | .svg | Vector scaling, sanitized for security |
| Word Documents | .docx | Formatted HTML output |
| Markdown | .md, .markdown | GitHub Flavored Markdown support |
| CSV | .csv | Table view with header row (max 1000 rows) |
| Plain Text | .txt | Monospace formatting |
Examples
Viewing Different Document Types
// 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');Handling Errors
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.');
}
}
});Tracking Page Changes (PDF)
render(container, 'https://example.com/document.pdf', {
onPageChange: (currentPage, totalPages) => {
// Update your UI with page information
document.getElementById('page-info').textContent =
`Page ${currentPage} of ${totalPages}`;
}
});Dynamic Document Loading
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');Styling the Container
<style>
#viewer {
width: 100%;
height: 600px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
<div id="viewer"></div>Format Detection
The library automatically detects document formats using:
- MIME type from the HTTP response
Content-Typeheader (primary) - File extension as a fallback when MIME type is ambiguous or missing
Common MIME types:
application/pdf→ PDFimage/png,image/jpeg, etc. → Imagesimage/svg+xml→ SVGapplication/vnd.openxmlformats-officedocument.wordprocessingml.document→ DOCXtext/markdown→ Markdowntext/csv→ CSVtext/plain→ Plain Text (or Markdown if.mdextension)
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
Desktop
- Zoom:
Ctrl/Cmd + Scroll(mouse wheel) - Zoom: Toolbar buttons (
+/-) - Pan: Click and drag when zoomed beyond fit-to-width
- Page Navigation: Toolbar buttons (
</>)
Mobile/Touch
- 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.comIf 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
# Install dependencies
npm install
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheckAI Acknowledgement & Development Status
This library was created with significant AI assistance and is currently in early alpha phase.
Current Status
- 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
What This Means
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
Future Plans
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
Contributing
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!
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
