Skip to content

Commit 59c8a7f

Browse files
committed
Added a PDF viewer snippet
1 parent dedf344 commit 59c8a7f

File tree

1 file changed

+62
-0
lines changed
  • Client-Side Components/UI Pages/PDF viewer page in tsx

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"use client";
2+
import { getDocument, GlobalWorkerOptions } from "pdfjs-dist/legacy/build/pdf.mjs";
3+
import { useEffect, useRef } from "react";
4+
5+
GlobalWorkerOptions.workerSrc = "/pdfjs/pdf.worker.min.mjs";
6+
7+
export default function PdfViewer({ file }: { file: File }) {
8+
const containerRef = useRef<HTMLDivElement>(null);
9+
const hasRendered = useRef(false);
10+
11+
useEffect(() => {
12+
if (!file || file.size === 0) return;
13+
if (hasRendered.current) return;
14+
15+
hasRendered.current = true;
16+
const container = containerRef.current;
17+
if (!container) return;
18+
19+
const renderPDF = async () => {
20+
container.innerHTML = "";
21+
22+
// Render PDF
23+
const arrayBuffer = await file.arrayBuffer();
24+
const pdf = await getDocument({ data: arrayBuffer }).promise;
25+
26+
// Render each page
27+
for (let i = 1; i <= pdf.numPages; i++) {
28+
// Render page
29+
const page = await pdf.getPage(i);
30+
const viewport = page.getViewport({ scale: 1.2 });
31+
32+
// Create canvas
33+
const canvas = document.createElement("canvas");
34+
const context = canvas.getContext("2d")!;
35+
canvas.height = viewport.height;
36+
canvas.width = viewport.width;
37+
38+
// Render page
39+
await page.render({ canvasContext: context, viewport }).promise;
40+
41+
// Add canvas to container
42+
canvas.id = `page_${i}`;
43+
container.appendChild(canvas);
44+
}
45+
};
46+
// Render PDF
47+
renderPDF();
48+
49+
return () => {
50+
// Clear on unmount
51+
if (container) container.innerHTML = "";
52+
};
53+
}, [file]);
54+
55+
return (
56+
// Render PDF
57+
<div
58+
ref={containerRef}
59+
className="pdf-container overflow-auto h-full shadow-xl"
60+
/>
61+
);
62+
}

0 commit comments

Comments
 (0)