Skip to main content

pdfium_render/
error.rs

1//! Defines the [PdfiumError] enum, used to wrap Pdfium errors as `Err` values.
2
3use crate::bindgen::{
4    FPDF_ERR_FILE, FPDF_ERR_FORMAT, FPDF_ERR_PAGE, FPDF_ERR_PASSWORD, FPDF_ERR_SECURITY,
5    FPDF_ERR_UNKNOWN,
6};
7use std::error::Error;
8use std::ffi::IntoStringError;
9use std::fmt::{Display, Formatter, Result};
10use std::num::ParseIntError;
11
12#[cfg(target_arch = "wasm32")]
13use wasm_bindgen::JsValue;
14
15#[cfg(doc)]
16use crate::pdfium::Pdfium;
17
18/// A wrapped internal library error from Pdfium's `FPDF_ERR_*` constant values.
19///
20/// Pdfium only provides detailed internal error information for document loading functions.
21/// All other functions in the Pdfium API return a value indicating success or failure,
22/// but otherwise detailed error information for failed API calls is not available. In these
23/// cases, an error value of [PdfiumInternalError::Unknown] will be returned.
24// For more information, see: https://github.com/ajrcarey/pdfium-render/issues/78
25#[derive(Debug)]
26pub enum PdfiumInternalError {
27    /// The document could not be loaded due to a file system error.
28    FileError = FPDF_ERR_FILE as isize,
29
30    /// The document could not be loaded due to a format parsing error.
31    FormatError = FPDF_ERR_FORMAT as isize,
32
33    /// The document could not be loaded because the wrong password was supplied.
34    PasswordError = FPDF_ERR_PASSWORD as isize,
35
36    /// The document could not be loaded because of the document's security settings.
37    SecurityError = FPDF_ERR_SECURITY as isize,
38
39    /// The page could not be loaded due to an internal error.
40    PageError = FPDF_ERR_PAGE as isize,
41
42    /// A generic error value returned in all other unhandled situations.
43    Unknown = FPDF_ERR_UNKNOWN as isize,
44}
45
46/// A wrapper enum for handling Pdfium errors as standard Rust `Err` values.
47#[derive(Debug)]
48pub enum PdfiumError {
49    /// The Pdfium WASM module has not been initialized.
50    ///
51    /// It is essential that the exported `initialize_pdfium_render()` function be called
52    /// from Javascript _before_ calling any `pdfium-render` function from within your Rust code.
53    /// See: <https://github.com/ajrcarey/pdfium-render/blob/master/examples/index.html>
54    #[cfg(target_arch = "wasm32")]
55    PdfiumWasmModuleNotInitialized,
56
57    /// An error occurred during dynamic binding to an external Pdfium library.
58    #[cfg(not(target_arch = "wasm32"))]
59    LoadLibraryError(libloading::Error),
60
61    /// An error occurred during dynamic binding while converting an FPDF_* function name
62    /// to a C string. The wrapped string value contains more information.
63    #[cfg(not(target_arch = "wasm32"))]
64    LoadLibraryFunctionNameError(String),
65
66    /// The global library bindings have already been initialized based on the
67    /// first call to [Pdfium::new]. Bindings initialization can only occur once
68    /// during the lifetime of the program.
69    PdfiumLibraryBindingsAlreadyInitialized,
70
71    UnrecognizedPath,
72    PdfClipPathSegmentIndexOutOfBounds,
73    PageIndexOutOfBounds,
74    LinkIndexOutOfBounds,
75    UnknownBitmapFormat,
76    UnknownBitmapRotation,
77    UnknownFormType,
78    UnknownFormFieldType,
79    UnknownActionType,
80    UnknownAppearanceMode,
81    UnknownPageAnnotationVariableTextJustificationType,
82    PageObjectIndexOutOfBounds,
83    PageAnnotationIndexOutOfBounds,
84    OwnershipNotAttachedToDocument,
85    OwnershipNotAttachedToPage,
86    OwnershipAlreadyAttachedToDifferentPage,
87    OwnershipNotAttachedToAnnotation,
88    FormFieldOptionIndexOutOfBounds,
89    FormFieldAppearanceStreamUndefined,
90    PageFlattenFailure,
91    PageMissingEmbeddedThumbnail,
92    UnknownPdfPageObjectType,
93    UnknownPdfPageTextRenderMode,
94    UnknownPdfPagePathFillMode,
95    UnknownPdfAnnotationType,
96    UnknownPdfDestinationViewType,
97    UnknownPdfSecurityHandlerRevision,
98    UnknownPdfSignatureModificationDetectionPermissionLevel,
99    UnsupportedPdfPageObjectType,
100    TextSegmentIndexOutOfBounds,
101    TextSearchTargetIsEmpty,
102    CharIndexOutOfBounds,
103    NoCharsInPageObject,
104    NoCharsInAnnotation,
105    NoCharsInRect,
106    ImageObjectFilterIndexOutOfBounds,
107    ImageObjectFilterIndexInBoundsButFilterUndefined,
108    UnknownPdfColorSpace,
109    InvalidTransformationMatrix,
110    SignatureIndexOutOfBounds,
111    AttachmentIndexOutOfBounds,
112    NoDataInAttachment,
113    FontGlyphIndexOutOfBounds,
114    UnknownPathSegmentType,
115    NoPagesInDocument,
116    NoPageObjectsInCollection,
117    NoPageLinksInCollection,
118    NoAnnotationsInCollection,
119    PageObjectNotCopyable,
120    ImageObjectFiltersNotCopyable,
121    PathObjectBezierControlPointsNotCopyable,
122    PathObjectUnknownSegmentTypeNotCopyable,
123    GroupContainsNonCopyablePageObjects,
124    SourcePageIndexNotInCache,
125    NoUriForAction,
126    DestinationPageIndexNotAvailable,
127    DestinationPageLocationNotAvailable,
128    PageAnnotationAttachmentPointIndexOutOfBounds,
129    NoAttachmentPointsInPageAnnotation,
130    CoordinateConversionFunctionIndicatedError,
131
132    /// Pdfium does not safely support moving page object ownership from one document to another.
133    CannotMoveObjectAcrossDocuments,
134
135    /// Pdfium does not support adding or removing page objects from the page objects
136    /// collection inside a PdfPageXObjectFormObject object.
137    PageObjectsCollectionIsImmutable,
138
139    /// A call to `FPDFDest_GetView()` returned a valid `FPDFDEST_VIEW_*` value, but the number
140    /// of view parameters returned does not match the PDF specification.
141    PdfDestinationViewInvalidParameters,
142
143    /// A [ParseIntError] occurred while attempting to parse a `PdfColor` from a hexadecimal string
144    /// in `PdfColor::from_hex()`.
145    ParseHexadecimalColorError(ParseIntError),
146
147    /// The hexadecimal string given to `PdfColor::from_hex()` was not either exactly 7 or 9
148    /// characters long.
149    ParseHexadecimalColorUnexpectedLength,
150
151    /// The leading `#` character was not found while attempting to parse a `PdfColor` from
152    /// a hexadecimal string in `PdfColor::from_hex()`.
153    ParseHexadecimalColorMissingLeadingHash,
154
155    /// An error occurred converting a byte stream into a `CString`.
156    CStringConversionError(IntoStringError),
157
158    /// Two data buffers are expected to have the same size, but they do not.
159    DataBufferLengthMismatch,
160
161    /// The setting cannot be returned because this `PdfPageGroupObject` is empty.
162    EmptyPageObjectGroup,
163
164    /// A call to a internal Pdfium `FPDF_*` function returned a value indicating failure.
165    ///
166    /// For Pdfium functions that return enumerations, this means the function returned
167    /// a value of -1 rather than a valid enumeration constant.
168    ///
169    /// For Pdfium functions that return C-style boolean integers, this means that the function
170    /// returned a value other than `PdfiumLibraryBindings::TRUE`.
171    PdfiumFunctionReturnValueIndicatedFailure,
172
173    /// A call to a Pdfium function that returns a standard 8-bit color component value
174    /// (for example, `FPDFPageObj_GetStrokeColor()` and `FPDFPageObj_GetStrokeColor()`)
175    /// successfully returned a value, but the value could not be converted from a c_int
176    /// to a standard Rust u8.
177    UnableToConvertPdfiumColorValueToRustu8(std::num::TryFromIntError),
178
179    /// The browser's built-in `Window` object could not be retrieved.
180    WebSysWindowObjectNotAvailable,
181
182    #[cfg(target_arch = "wasm32")]
183    /// A JsValue returned from a function call was set to JsValue::UNDEFINED instead of
184    /// a valid value of the expected type.
185    JsValueUndefined,
186
187    #[cfg(target_arch = "wasm32")]
188    /// An error was returned when attempting to use the browser's built-in `fetch()` API.
189    WebSysFetchError(JsValue),
190
191    #[cfg(target_arch = "wasm32")]
192    /// An invalid Response object was returned when attempting to use the browser's built-in `fetch()` API.
193    WebSysInvalidResponseError,
194
195    #[cfg(target_arch = "wasm32")]
196    /// An error was returned when attempting to construct a `Blob` object from a byte buffer.
197    JsSysErrorConstructingBlobFromBytes,
198
199    #[cfg(target_arch = "wasm32")]
200    /// An error occurred when attempting to retrieve the function table for the compiled
201    /// Pdfium WASM module.
202    JsSysErrorRetrievingFunctionTable(JsValue),
203
204    #[cfg(target_arch = "wasm32")]
205    /// An error occurred when attempting to retrieve an exported function from
206    /// `pdfium-render`'s WASM module.
207    JsSysErrorRetrievingFunction(JsValue),
208
209    #[cfg(target_arch = "wasm32")]
210    /// An error occurred when attempting to update an entry in Pdfium's WASM function table.
211    JsSysErrorPatchingFunctionTable(JsValue),
212
213    #[cfg(target_arch = "wasm32")]
214    /// No previously cached function was available for a WASM function table restore operation.
215    ///
216    /// This error should never occur; if it does, it indicates a programming error in pdfium-render.
217    /// Please file an issue: https://github.com/ajrcarey/pdfium-render/issues
218    NoPreviouslyCachedFunctionSet,
219
220    /// An error occurred during an image processing operation.
221    ImageError,
222
223    /// Dimensions of `Image::Image` are specified in `u32`, but bitmaps in Pdfium are sized in
224    /// `c_int` (`i32`), meaning that an `Image::Image` can have dimensions that overflow
225    /// the maximum size of a Pdfium bitmap. As a compromise, Image dimensions in `pdfium-render`
226    /// are limited to `u16`.
227    ///
228    /// This error indicates that an `Image::Image` had a width or height larger than the maximum
229    /// `u16` size allowed by `pdfium-render`.
230    ImageSizeOutOfBounds,
231
232    /// An I/O error occurred during a Pdfium file operation.
233    IoError(std::io::Error),
234
235    /// A wrapped internal library error from Pdfium's `FPDF_ERR_*` constant values.
236    PdfiumLibraryInternalError(PdfiumInternalError),
237}
238
239impl Display for PdfiumError {
240    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
241        write!(f, "{self:#?}")
242    }
243}
244
245impl Error for PdfiumError {}