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, NulError};
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    NoTextSegmentsInPageText,
101    TextSegmentIndexOutOfBounds,
102    TextSearchTargetIsEmpty,
103    NoCharsInPageTextChars,
104    CharIndexOutOfBounds,
105    NoCharsInPageObject,
106    NoCharsInAnnotation,
107    NoCharsInRect,
108    ImageObjectFilterIndexOutOfBounds,
109    ImageObjectFilterIndexInBoundsButFilterUndefined,
110    UnknownPdfColorSpace,
111    InvalidTransformationMatrix,
112    SignatureIndexOutOfBounds,
113    AttachmentIndexOutOfBounds,
114    NoDataInAttachment,
115    FontGlyphIndexOutOfBounds,
116    UnknownPathSegmentType,
117    NoPagesInDocument,
118    NoPageObjectsInCollection,
119    NoPageLinksInCollection,
120    NoAnnotationsInCollection,
121    PageObjectNotCopyable,
122    ImageObjectFiltersNotCopyable,
123    PathObjectBezierControlPointsNotCopyable,
124    PathObjectUnknownSegmentTypeNotCopyable,
125    GroupContainsNonCopyablePageObjects,
126    SourcePageIndexNotInCache,
127    NoUriForAction,
128    DestinationPageIndexNotAvailable,
129    DestinationPageLocationNotAvailable,
130    PageAnnotationAttachmentPointIndexOutOfBounds,
131    NoAttachmentPointsInPageAnnotation,
132    CoordinateConversionFunctionIndicatedError,
133
134    /// Pdfium does not safely support moving page object ownership from one document to another.
135    CannotMoveObjectAcrossDocuments,
136
137    /// Pdfium does not support adding or removing page objects from the page objects
138    /// collection inside a PdfPageXObjectFormObject object.
139    PageObjectsCollectionIsImmutable,
140
141    /// A call to `FPDFDest_GetView()` returned a valid `FPDFDEST_VIEW_*` value, but the number
142    /// of view parameters returned does not match the PDF specification.
143    PdfDestinationViewInvalidParameters,
144
145    /// A [ParseIntError] occurred while attempting to parse a `PdfColor` from a hexadecimal string
146    /// in `PdfColor::from_hex()`.
147    ParseHexadecimalColorError(ParseIntError),
148
149    /// The hexadecimal string given to `PdfColor::from_hex()` was not either exactly 7 or 9
150    /// characters long.
151    ParseHexadecimalColorUnexpectedLength,
152
153    /// The leading `#` character was not found while attempting to parse a `PdfColor` from
154    /// a hexadecimal string in `PdfColor::from_hex()`.
155    ParseHexadecimalColorMissingLeadingHash,
156
157    /// An error occurred converting a byte stream into a `CString`.
158    CStringConversionError(IntoStringError),
159
160    /// Two data buffers are expected to have the same size, but they do not.
161    DataBufferLengthMismatch,
162
163    /// The setting cannot be returned because this `PdfPageGroupObject` is empty.
164    EmptyPageObjectGroup,
165
166    /// A call to a internal Pdfium `FPDF_*` function returned a value indicating failure.
167    ///
168    /// For Pdfium functions that return enumerations, this means the function returned
169    /// a value of -1 rather than a valid enumeration constant.
170    ///
171    /// For Pdfium functions that return C-style boolean integers, this means that the function
172    /// returned a value other than `PdfiumLibraryBindings::TRUE`.
173    PdfiumFunctionReturnValueIndicatedFailure,
174
175    /// A call to a Pdfium function that returns a standard 8-bit color component value
176    /// (for example, `FPDFPageObj_GetStrokeColor()` and `FPDFPageObj_GetStrokeColor()`)
177    /// successfully returned a value, but the value could not be converted from a c_int
178    /// to a standard Rust u8.
179    UnableToConvertPdfiumColorValueToRustu8(std::num::TryFromIntError),
180
181    /// The browser's built-in `Window` object could not be retrieved.
182    WebSysWindowObjectNotAvailable,
183
184    #[cfg(target_arch = "wasm32")]
185    /// A JsValue returned from a function call was set to JsValue::UNDEFINED instead of
186    /// a valid value of the expected type.
187    JsValueUndefined,
188
189    #[cfg(target_arch = "wasm32")]
190    /// An error was returned when attempting to use the browser's built-in `fetch()` API.
191    WebSysFetchError(JsValue),
192
193    #[cfg(target_arch = "wasm32")]
194    /// An invalid Response object was returned when attempting to use the browser's built-in `fetch()` API.
195    WebSysInvalidResponseError,
196
197    #[cfg(target_arch = "wasm32")]
198    /// An error was returned when attempting to construct a `Blob` object from a byte buffer.
199    JsSysErrorConstructingBlobFromBytes,
200
201    #[cfg(target_arch = "wasm32")]
202    /// An error occurred when attempting to retrieve the function table for the compiled
203    /// Pdfium WASM module.
204    JsSysErrorRetrievingFunctionTable(JsValue),
205
206    #[cfg(target_arch = "wasm32")]
207    /// An error occurred when attempting to retrieve an exported function from
208    /// `pdfium-render`'s WASM module.
209    JsSysErrorRetrievingFunction(JsValue),
210
211    #[cfg(target_arch = "wasm32")]
212    /// An error occurred when attempting to update an entry in Pdfium's WASM function table.
213    JsSysErrorPatchingFunctionTable(JsValue),
214
215    #[cfg(target_arch = "wasm32")]
216    /// No previously cached function was available for a WASM function table restore operation.
217    ///
218    /// This error should never occur; if it does, it indicates a programming error in pdfium-render.
219    /// Please file an issue: https://github.com/ajrcarey/pdfium-render/issues
220    NoPreviouslyCachedFunctionSet,
221
222    /// An error occurred during an image processing operation.
223    ImageError,
224
225    /// Dimensions of `Image::Image` are specified in `u32`, but bitmaps in Pdfium are sized in
226    /// `c_int` (`i32`), meaning that an `Image::Image` can have dimensions that overflow
227    /// the maximum size of a Pdfium bitmap. As a compromise, Image dimensions in `pdfium-render`
228    /// are limited to `u16`.
229    ///
230    /// This error indicates that an `Image::Image` had a width or height larger than the maximum
231    /// `u16` size allowed by `pdfium-render`.
232    ImageSizeOutOfBounds,
233
234    /// An I/O error occurred during a Pdfium file operation.
235    IoError(std::io::Error),
236
237    /// An error occurred during conversion of a given user font path to a CString.
238    InvalidUserFontPath(NulError),
239
240    /// A wrapped internal library error from Pdfium's `FPDF_ERR_*` constant values.
241    PdfiumLibraryInternalError(PdfiumInternalError),
242}
243
244impl Display for PdfiumError {
245    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
246        write!(f, "{self:#?}")
247    }
248}
249
250impl Error for PdfiumError {}