FPDF_LoadMemDocument

FPDF_LoadMemDocument(data_buf, size, password)

Description

Loads a PDF document from memory. This function is one of the primary ways to open a PDF document when you have the PDF data available in memory (e.g., after downloading a PDF file using fetch).

Prerequisites

This example uses the initializePdfium helper function from our Getting Started guide. Make sure to include this function in your code before trying the examples below.

Parameters

NameTypeDescription
data_bufnumberPointer to a memory buffer containing the PDF data. Must be allocated using pdfium.pdfium.wasmExports.malloc().
sizenumberSize of the PDF data in bytes.
passwordnumberPointer to a null-terminated UTF-8 string containing the password for encrypted documents, or 0 for no password.

Return Value

Returns a document handle (a number) on success, or 0 on failure. When a failure occurs, you can call FPDF_GetLastError() to retrieve an error code that provides more information about what went wrong.

Error Codes

CodeMeaning
0Success (no error)
1Unknown error
2File not found or could not be opened
3File not in PDF format or corrupted
4Password required or incorrect password
5Unsupported security scheme
6Page not found or content error

Example

// Note: The initializePdfium function is a helper that initializes the PDFium library. // For the full implementation, see: /docs/pdfium/getting-started import { init, WrappedPdfiumModule } from '@embedpdf/pdfium'; // Create a singleton for PDFium instance let pdfiumInstance: WrappedPdfiumModule | null = null; async function initializePdfium() { if (pdfiumInstance) return pdfiumInstance; const response = await fetch('https://cdn.jsdelivr.net/npm/@embedpdf/pdfium/dist/pdfium.wasm'); const wasmBinary = await response.arrayBuffer(); pdfiumInstance = await init({ wasmBinary }); // Initialize the PDFium extension library pdfiumInstance.PDFiumExt_Init(); return pdfiumInstance; } async function loadPdfFromMemory(pdfData: Uint8Array) { // Initialize PDFium WASM module (will reuse existing instance if available) const pdfium = await initializePdfium(); // Allocate memory for the PDF data const filePtr = pdfium.pdfium.wasmExports.malloc(pdfData.length); // Copy the PDF data to the allocated memory pdfium.pdfium.HEAPU8.set(pdfData, filePtr); // For password-protected PDFs, set up a password // For unprotected PDFs, you can pass 0 for the password // const passwordPtr = pdfium.pdfium.wasmExports.malloc(passwordString.length + 1); // pdfium.pdfium.stringToUTF8(passwordString, passwordPtr, passwordString.length + 1); // Load the PDF document const docPtr = pdfium.FPDF_LoadMemDocument(filePtr, pdfData.length, 0); if (!docPtr) { // Get the error code const error = pdfium.FPDF_GetLastError(); // Map error code to message let errorMessage = 'Unknown error'; switch (error) { case 1: errorMessage = 'Unknown error'; break; case 2: errorMessage = 'File not found or could not be opened'; break; case 3: errorMessage = 'File not in PDF format or corrupted'; break; case 4: errorMessage = 'Password required or incorrect password'; break; case 5: errorMessage = 'Unsupported security scheme'; break; case 6: errorMessage = 'Page not found or content error'; break; } // Clean up allocated memory pdfium.pdfium.wasmExports.free(filePtr); // pdfium.pdfium.wasmExports.free(passwordPtr); // If using a password throw new Error(`Failed to load PDF: ${errorMessage} (code ${error})`); } // Free the memory used for the PDF data since it's been loaded into the document pdfium.pdfium.wasmExports.free(filePtr); // pdfium.pdfium.wasmExports.free(passwordPtr); // If using a password return { pdfium, docPtr }; } // Usage example async function exampleUsage() { try { // Fetch a PDF file const response = await fetch('sample.pdf'); const buffer = await response.arrayBuffer(); const pdfData = new Uint8Array(buffer); // Load the PDF document const { pdfium, docPtr } = await loadPdfFromMemory(pdfData); // Now you can use the document for various operations // For example, get the page count const pageCount = pdfium.FPDF_GetPageCount(docPtr); console.log(`PDF loaded successfully with ${pageCount} pages`); // Perform other operations with the document... // When done, close the document to free resources pdfium.FPDF_CloseDocument(docPtr); } catch (error) { console.error('Error handling PDF:', error); } } exampleUsage();

Notes

  • Always free the memory allocated for data_buf using pdfium.pdfium.wasmExports.free() when you’re done with it, even if FPDF_LoadMemDocument fails.
  • Similarly, if you allocated memory for a password string, make sure to free that memory as well.
  • When you’re done with the document, call FPDF_CloseDocument(docPtr) to release the document’s resources.
  • This function is commonly used in web applications to load PDFs that have been downloaded using fetch or uploaded by the user.
  • For very large documents, consider using FPDF_LoadCustomDocument instead, which allows for on-demand loading of PDF data.
Last updated on March 31, 2025