Skip to content

Instantly share code, notes, and snippets.

@omimouni
Created February 22, 2025 17:42
Show Gist options
  • Save omimouni/030b05bb10b3ada484e338c61b4ea588 to your computer and use it in GitHub Desktop.
Save omimouni/030b05bb10b3ada484e338c61b4ea588 to your computer and use it in GitHub Desktop.
The PdfViewer React component converts a PDF into images by rendering each page onto a canvas and displaying them as base64 PNG images.
import React, { useState } from "react";
import * as pdfjs from "pdfjs-dist/build/pdf";
import "pdfjs-dist/build/pdf.worker.min.mjs";
// PdfViewer component that renders the PDF as images
const PdfViewer = ({ pdfUrl }) => {
// State to hold the rendered images and loading status
const [images, setImages] = useState([]);
const [loading, setLoading] = useState(false);
// Function to load and render the PDF when the button is clicked
const handleRenderPdf = async () => {
setLoading(true); // Start loading state
try {
// Get the PDF document
const loadingTask = pdfjs.getDocument({ url: pdfUrl, withCredentials: false });
const pdf = await loadingTask.promise;
let imageList = []; // Array to store images of each page
// Loop through all pages of the PDF
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i); // Get each page
const viewport = page.getViewport({ scale: 2 }); // Set scale for better quality
// Create a canvas element to render the page as an image
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render the page onto the canvas
await page.render({ canvasContext: context, viewport }).promise;
imageList.push(canvas.toDataURL("image/png")); // Save the page image as base64
}
setImages(imageList); // Set the images array after all pages are rendered
} catch (error) {
console.error("Error loading PDF:", error); // Handle any errors
} finally {
setLoading(false); // Stop loading once done
}
};
return (
<div>
{/* Button to trigger PDF rendering */}
<button onClick={handleRenderPdf} disabled={loading}>
{loading ? "Compiling..." : "Compile PDF to Images"}
</button>
{/* Display loading message */}
{loading && <p>Loading PDF...</p>}
{/* Display images of PDF pages if available */}
{!loading && images.length > 0 && (
<div>
{images.map((src, index) => (
<img
key={index}
src={src} // The rendered image
alt={`Page ${index + 1}`} // Alt text for the image
style={{ width: "100%", marginBottom: "10px" }} // Image styling
/>
))}
</div>
)}
</div>
);
};
export default PdfViewer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment