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 InvalidFontSize,
134 NoLanguageSetInDocumentCatalog,
135
136 /// Pdfium does not safely support moving page object ownership from one document to another.
137 CannotMoveObjectAcrossDocuments,
138
139 /// Pdfium does not support adding or removing page objects from the page objects
140 /// collection inside a PdfPageXObjectFormObject object.
141 PageObjectsCollectionIsImmutable,
142
143 /// A call to `FPDFDest_GetView()` returned a valid `FPDFDEST_VIEW_*` value, but the number
144 /// of view parameters returned does not match the PDF specification.
145 PdfDestinationViewInvalidParameters,
146
147 /// A [ParseIntError] occurred while attempting to parse a `PdfColor` from a hexadecimal string
148 /// in `PdfColor::from_hex()`.
149 ParseHexadecimalColorError(ParseIntError),
150
151 /// The hexadecimal string given to `PdfColor::from_hex()` was not either exactly 7 or 9
152 /// characters long.
153 ParseHexadecimalColorUnexpectedLength,
154
155 /// The leading `#` character was not found while attempting to parse a `PdfColor` from
156 /// a hexadecimal string in `PdfColor::from_hex()`.
157 ParseHexadecimalColorMissingLeadingHash,
158
159 /// An error occurred converting a byte stream into a `CString`.
160 CStringConversionError(IntoStringError),
161
162 /// Two data buffers are expected to have the same size, but they do not.
163 DataBufferLengthMismatch,
164
165 /// The setting cannot be returned because this `PdfPageGroupObject` is empty.
166 EmptyPageObjectGroup,
167
168 /// A call to a internal Pdfium `FPDF_*` function returned a value indicating failure.
169 ///
170 /// For Pdfium functions that return enumerations, this means the function returned
171 /// a value of -1 rather than a valid enumeration constant.
172 ///
173 /// For Pdfium functions that return C-style boolean integers, this means that the function
174 /// returned a value other than `PdfiumLibraryBindings::TRUE`.
175 PdfiumFunctionReturnValueIndicatedFailure,
176
177 /// A call to a Pdfium function that returns a standard 8-bit color component value
178 /// (for example, `FPDFPageObj_GetStrokeColor()` and `FPDFPageObj_GetStrokeColor()`)
179 /// successfully returned a value, but the value could not be converted from a c_int
180 /// to a standard Rust u8.
181 UnableToConvertPdfiumColorValueToRustu8(std::num::TryFromIntError),
182
183 /// The browser's built-in `Window` object could not be retrieved.
184 WebSysWindowObjectNotAvailable,
185
186 #[cfg(target_arch = "wasm32")]
187 /// A JsValue returned from a function call was set to JsValue::UNDEFINED instead of
188 /// a valid value of the expected type.
189 JsValueUndefined,
190
191 #[cfg(target_arch = "wasm32")]
192 /// An error was returned when attempting to use the browser's built-in `fetch()` API.
193 WebSysFetchError(JsValue),
194
195 #[cfg(target_arch = "wasm32")]
196 /// An invalid Response object was returned when attempting to use the browser's built-in `fetch()` API.
197 WebSysInvalidResponseError,
198
199 #[cfg(target_arch = "wasm32")]
200 /// An error was returned when attempting to construct a `Blob` object from a byte buffer.
201 JsSysErrorConstructingBlobFromBytes,
202
203 #[cfg(target_arch = "wasm32")]
204 /// An error occurred when attempting to retrieve the function table for the compiled
205 /// Pdfium WASM module.
206 JsSysErrorRetrievingFunctionTable(JsValue),
207
208 #[cfg(target_arch = "wasm32")]
209 /// An error occurred when attempting to retrieve an exported function from
210 /// `pdfium-render`'s WASM module.
211 JsSysErrorRetrievingFunction(JsValue),
212
213 #[cfg(target_arch = "wasm32")]
214 /// An error occurred when attempting to update an entry in Pdfium's WASM function table.
215 JsSysErrorPatchingFunctionTable(JsValue),
216
217 #[cfg(target_arch = "wasm32")]
218 /// No previously cached function was available for a WASM function table restore operation.
219 ///
220 /// This error should never occur; if it does, it indicates a programming error in pdfium-render.
221 /// Please file an issue: https://github.com/ajrcarey/pdfium-render/issues
222 NoPreviouslyCachedFunctionSet,
223
224 /// An error occurred during an image processing operation.
225 ImageError,
226
227 /// Dimensions of `Image::Image` are specified in `u32`, but bitmaps in Pdfium are sized in
228 /// `c_int` (`i32`), meaning that an `Image::Image` can have dimensions that overflow
229 /// the maximum size of a Pdfium bitmap. As a compromise, Image dimensions in `pdfium-render`
230 /// are limited to `u16`.
231 ///
232 /// This error indicates that an `Image::Image` had a width or height larger than the maximum
233 /// `u16` size allowed by `pdfium-render`.
234 ImageSizeOutOfBounds,
235
236 #[cfg(not(target_arch = "wasm32"))]
237 /// When constructing a [crate::pdf::bitmap::PdfBitmap] from a raw buffer, the buffer
238 /// must be large enough to contain the bitmap's pixels.
239 ///
240 /// The method which returns this error is not available on WASM.
241 ImageBufferTooSmall,
242
243 /// An I/O error occurred during a Pdfium file operation.
244 IoError(std::io::Error),
245
246 /// An error occurred during conversion of a given user font path to a CString.
247 InvalidUserFontPath(NulError),
248
249 /// Pdfium does not include a default font provider implementation for the current platform.
250 NoPlatformDefaultFontProvider,
251
252 /// A wrapped internal library error from Pdfium's `FPDF_ERR_*` constant values.
253 PdfiumLibraryInternalError(PdfiumInternalError),
254}
255
256impl Display for PdfiumError {
257 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
258 write!(f, "{self:#?}")
259 }
260}
261
262impl Error for PdfiumError {}