Render pages on canvas in our JavaScript PDF viewer
With Nutrient Web SDK, it’s possible to render a single PDF page as an image and insert it into a canvas element. To do so, you can retrieve a single PDF page as an ArrayBuffer:
async function appendCanvas() { // Configuration for loading the PDF document. const configuration = { container: "#pspdfkit", document: "document.pdf", licenseKey: "YOUR_LICENSE_KEY" // Replace with your actual license key. };
try { const instance = await NutrientViewer.load(configuration);
const pageWidth = instance.pageInfoForIndex(0).width; const pageHeight = instance.pageInfoForIndex(0).height;
const width = 400; const height = Math.round((width * pageHeight) / pageWidth);
// Renders the first page (page index 0). const buffer = await instance.renderPageAsArrayBuffer({ width: width }, 0);
const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height;
const imageView = new Uint8Array(buffer); const ctx = canvas.getContext("2d"); const imageData = ctx.createImageData(width, height); imageData.data.set(imageView); ctx.putImageData(imageData, 0, 0);
document.body.appendChild(canvas); } catch (error) { console.error("Failed to render page to canvas:", error.message); throw error; }}Complete runnable example
Here’s a complete HTML example that you can use as a starting point:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Render PDF Page to Canvas</title> <style> /* Hide the main viewer container since we only want the canvas output */ #pspdfkit { width: 1px; height: 1px; position: absolute; left: -9999px; } #canvas-container { padding: 20px; } canvas { border: 1px solid #ccc; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); } .error { color: #dc3545; padding: 20px; } </style></head><body> <!-- Hidden container for the Nutrient viewer instance --> <div id="pspdfkit"></div>
<!-- Container where the canvas will be appended --> <div id="canvas-container"></div>
<!-- Note: The CDN script exposes the global as PSPDFKit (legacy name). Use PSPDFKit.load() with the CDN, or NutrientViewer.load() with npm package. --> <script src="https://cdn.cloud.pspdfkit.com/pspdfkit-web/latest/pspdfkit.js"></script> <script> async function renderPageToCanvas(documentPath, pageIndex = 0, canvasWidth = 400) { const configuration = { container: "#pspdfkit", document: documentPath, licenseKey: "YOUR_LICENSE_KEY" // Replace with your actual license key. };
let instance = null;
try { // Use PSPDFKit when loading from CDN, or `NutrientViewer` with the npm package. instance = await PSPDFKit.load(configuration);
// Get the page dimensions. const pageInfo = instance.pageInfoForIndex(pageIndex); if (!pageInfo) { throw new Error(`Page ${pageIndex} does not exist in the document`); }
const pageWidth = pageInfo.width; const pageHeight = pageInfo.height; const canvasHeight = Math.round((canvasWidth * pageHeight) / pageWidth);
// Render the page to an ArrayBuffer. const buffer = await instance.renderPageAsArrayBuffer( { width: canvasWidth }, pageIndex );
// Create and configure the canvas. const canvas = document.createElement("canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight;
// Draw the image data to the canvas. const imageView = new Uint8Array(buffer); const ctx = canvas.getContext("2d"); const imageData = ctx.createImageData(canvasWidth, canvasHeight); imageData.data.set(imageView); ctx.putImageData(imageData, 0, 0);
// Append to the container. document.getElementById("canvas-container").appendChild(canvas);
console.log(`Successfully rendered page ${pageIndex} to canvas`); return canvas;
} catch (error) { console.error("Failed to render page to canvas:", error);
const errorDiv = document.createElement("div"); errorDiv.className = "error"; errorDiv.textContent = `Error: ${error.message}`; document.getElementById("canvas-container").appendChild(errorDiv);
throw error; } finally { // Clean up the viewer instance. if (instance) { PSPDFKit.unload(instance); } } }
// Render the first page when the page loads. document.addEventListener("DOMContentLoaded", () => { renderPageToCanvas("document.pdf", 0, 600); }); </script></body></html>Rendering multiple pages
To render multiple pages to separate canvas elements:
async function renderMultiplePages(documentPath, pageIndices, canvasWidth = 400) { const configuration = { container: "#pspdfkit", document: documentPath, licenseKey: "YOUR_LICENSE_KEY" };
let instance = null; const canvases = [];
try { // Use PSPDFKit when loading from CDN, or `NutrientViewer` with the npm package. instance = await PSPDFKit.load(configuration); const totalPages = instance.totalPageCount;
for (const pageIndex of pageIndices) { if (pageIndex < 0 || pageIndex >= totalPages) { console.warn(`Skipping invalid page index: ${pageIndex}`); continue; }
const pageInfo = instance.pageInfoForIndex(pageIndex); const canvasHeight = Math.round((canvasWidth * pageInfo.height) / pageInfo.width);
const buffer = await instance.renderPageAsArrayBuffer({ width: canvasWidth }, pageIndex);
const canvas = document.createElement("canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight;
const ctx = canvas.getContext("2d"); const imageData = ctx.createImageData(canvasWidth, canvasHeight); imageData.data.set(new Uint8Array(buffer)); ctx.putImageData(imageData, 0, 0);
canvases.push(canvas); }
return canvases;
} catch (error) { console.error("Failed to render pages:", error); throw error; } finally { if (instance) { PSPDFKit.unload(instance); } }}
// Example: Render pages 0, 2, and 4.renderMultiplePages("document.pdf", [0, 2, 4]).then(canvases => { const container = document.getElementById("canvas-container"); canvases.forEach(canvas => container.appendChild(canvas));});