This guide demonstrates a complete PDF processing workflow using React and Vite:
The example shows a simple React component with minimal styling and direct PDF SDK integration.
Create src/components/PdfViewer.jsx:
import { useState, useEffect, useRef } from 'react';
import { PdfSdk } from '@avanquest/pdf-web-viewer/sdk';
const PdfViewer = () => {
const [status, setStatus] = useState('');
const [isInitialized, setIsInitialized] = useState(false);
const openDocumentsRef = useRef([]);
const updateStatus = (message) => {
setStatus(message);
};
const downloadFile = (file, fileName) => {
const blob = new Blob([file], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const a = Object.assign(document.createElement('a'), {
href: url,
download: fileName,
});
a.click();
URL.revokeObjectURL(url);
};
const initPdfSdk = async () => {
try {
await PdfSdk.initialize({
license: import.meta.env.VITE_PDF_LICENSE_KEY || 'YOUR_LICENSE_KEY',
workerPath: import.meta.env.VITE_WORKER_PATH || '/workers',
});
setIsInitialized(true);
} catch (error) {
console.error('Error initializing PDF SDK:', error);
updateStatus('Failed to initialize PDF SDK');
}
};
const handleUnload = async () => {
for (const doc of openDocumentsRef.current) {
await doc.dispose();
}
openDocumentsRef.current = [];
};
const handleFileInputChange = async (e) => {
const file = e.target.files?.[0];
if (!file || !isInitialized) return;
try {
const document = await PdfSdk.openDocument({ file });
openDocumentsRef.current.push(document);
/* Example operation: get page count */
const pageCount = document.getNumPages();
console.log(`Document has ${pageCount} pages`);
const savedFile = await document.exportDocument({ as: 'uint8array' });
if (savedFile) downloadFile(savedFile, file.name);
await document.dispose();
openDocumentsRef.current = openDocumentsRef.current.filter((d) => d !== document);
updateStatus('✅ PDF processed successfully');
} catch (err) {
console.error('Error during PDF processing:', err);
updateStatus('❌ Failed to process PDF');
}
};
useEffect(() => {
initPdfSdk();
return () => {
handleUnload();
};
}, []);
return (
<div style={{ padding: '40px', textAlign: 'center' }}>
<h1>PDF Web SDK Demo</h1>
<div style={{ background: '#f9f9f9', padding: '30px', borderRadius: '12px', display: 'inline-block' }}>
<input
type="file"
accept=".pdf"
onChange={handleFileInputChange}
disabled={!isInitialized}
style={{ marginBottom: '20px', padding: '10px' }}
/>
<div>{status}</div>
</div>
</div>
);
};
export default PdfViewer;
Update src/App.jsx:
import PdfViewer from './components/PdfViewer';
function App() {
return (
<div>
<h1>PDF Web Viewer React Integration</h1>
<PdfViewer />
</div>
);
}
export default App;
Start development server:
npm run dev
Open browser at http://localhost:5173.