FPDF_GetLastError
FPDF_GetLastError()
Description
Retrieves the error code for the last failed PDFium operation. This function is particularly useful after PDF document loading functions (like FPDF_LoadMemDocument
) return null, indicating a failure. The error code provides more information about what went wrong.
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
This function doesn’t take any parameters.
Return Value
Returns an integer error code indicating the cause of the last error. The meaning of each error code is as follows:
Code | Constant | Meaning |
---|---|---|
0 | FPDF_ERR_SUCCESS | No error (success) |
1 | FPDF_ERR_UNKNOWN | Unknown error |
2 | FPDF_ERR_FILE | File not found or could not be opened |
3 | FPDF_ERR_FORMAT | File not in PDF format or corrupted |
4 | FPDF_ERR_PASSWORD | Password required or incorrect password |
5 | FPDF_ERR_SECURITY | Unsupported security scheme |
6 | FPDF_ERR_PAGE | Page not found or content error |
7 | FPDF_ERR_XFALOAD | XFA load error |
8 | FPDF_ERR_XFALAYOUT | XFA layout error |
Interactive Example
Try opening a password-protected PDF with and without a password. This example demonstrates how to handle the common error code 4 (password required):
Example
// Note: The initializePdfium function is a helper that initializes the PDFium library.
// For the full implementation, see: /docs/pdfium/getting-started
import { initializePdfium } from './initialize-pdfium';
async function openProtectedPdf(pdfData: Uint8Array, password?: string) {
// Step 1: Initialize PDFium
const pdfium = await initializePdfium();
// Step 2: Load the PDF document
const filePtr = pdfium.pdfium.wasmExports.malloc(pdfData.length);
pdfium.pdfium.HEAPU8.set(pdfData, filePtr);
// Convert password to null-terminated UTF-8 string pointer if provided
let passwordPtr = 0;
if (password) {
const encoder = new TextEncoder();
const passwordBytes = encoder.encode(password + '\0');
passwordPtr = pdfium.pdfium.wasmExports.malloc(passwordBytes.length);
pdfium.pdfium.HEAPU8.set(passwordBytes, passwordPtr);
}
// Try to load the PDF document with optional password
const docPtr = pdfium.FPDF_LoadMemDocument(filePtr, pdfData.length, passwordPtr);
// Clean up password memory if allocated
if (passwordPtr) {
pdfium.pdfium.wasmExports.free(passwordPtr);
}
// Check if document loaded successfully
if (!docPtr) {
const errorCode = pdfium.FPDF_GetLastError();
pdfium.pdfium.wasmExports.free(filePtr);
// Map error code to a message
let errorMessage;
switch (errorCode) {
case 0: errorMessage = 'No error'; break;
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;
case 7: errorMessage = 'XFA load error'; break;
case 8: errorMessage = 'XFA layout error'; break;
default: errorMessage = `Unknown error code: ${errorCode}`; break;
}
// Return error details
return {
success: false,
errorCode,
errorMessage
};
}
try {
// Document loaded successfully - get basic info
const pageCount = pdfium.FPDF_GetPageCount(docPtr);
return {
success: true,
pageCount,
errorCode: 0,
errorMessage: 'PDF opened successfully'
};
} finally {
// Clean up resources
pdfium.FPDF_CloseDocument(docPtr);
pdfium.pdfium.wasmExports.free(filePtr);
}
}
// Usage example
async function handlePdfWithPasswordCheck() {
try {
// First try without password
const response = await fetch('protected.pdf');
const buffer = await response.arrayBuffer();
const pdfData = new Uint8Array(buffer);
let result = await openProtectedPdf(pdfData);
if (!result.success && result.errorCode === 4) {
console.log('PDF requires a password');
// Get password from user (simplified for example)
const password = prompt('Please enter the PDF password:');
if (password) {
// Try again with password
result = await openProtectedPdf(pdfData, password);
if (result.success) {
console.log(`Successfully opened PDF with ${result.pageCount} pages`);
} else {
console.error(`Failed to open PDF: ${result.errorMessage}`);
}
}
} else if (result.success) {
console.log(`Successfully opened PDF with ${result.pageCount} pages`);
} else {
console.error(`Failed to open PDF: ${result.errorMessage}`);
}
} catch (error) {
console.error('Error processing PDF:', error);
}
}
Best Practices
-
Always check for errors: After operations that might fail (especially document loading), check for errors using
FPDF_GetLastError
if the function returns an error indicator. -
Provide meaningful error messages: Map the error codes to descriptive error messages to help users understand what went wrong.
-
Handle specific error types: Different error codes call for different responses. For example, a password error (code 4) might prompt the user for a password, while a format error (code 3) might indicate the file is corrupt.
-
Clean up resources: Even when errors occur, make sure to free allocated memory and close any resources that were successfully opened.
-
Error context: When throwing errors based on PDFium error codes, include additional context about the operation that failed to make debugging easier.
Error Handling Strategies
-
Password-protected PDFs: If you get error code 4 (password required), you can prompt the user for a password and try loading the document again.
-
Corrupted files: Error code 3 often indicates file corruption. Consider validating PDF files before attempting to open them.
-
Missing files: Error code 2 suggests the file wasn’t found. Check file paths and availability.
-
XFA forms: Error codes 7 and 8 relate to XFA forms, which are a complex form technology in PDFs. PDFium has limited support for XFA forms.
Related Functions
- FPDF_LoadMemDocument - Load a PDF document from memory
- FPDF_CloseDocument - Close a loaded PDF document