pdfium-render 0.7.31

A high-level idiomatic Rust wrapper around Pdfium, the C++ PDF library used by the Google Chromium project.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
//! Defines the [PdfPageObject] enum, exposing functionality related to a single page object.

use crate::bindgen::{
    FPDF_ANNOTATION, FPDF_LINECAP_BUTT, FPDF_LINECAP_PROJECTING_SQUARE, FPDF_LINECAP_ROUND,
    FPDF_LINEJOIN_BEVEL, FPDF_LINEJOIN_MITER, FPDF_LINEJOIN_ROUND, FPDF_PAGE, FPDF_PAGEOBJECT,
    FPDF_PAGEOBJ_FORM, FPDF_PAGEOBJ_IMAGE, FPDF_PAGEOBJ_PATH, FPDF_PAGEOBJ_SHADING,
    FPDF_PAGEOBJ_TEXT, FPDF_PAGEOBJ_UNKNOWN,
};
use crate::bindings::PdfiumLibraryBindings;
use crate::color::PdfColor;
use crate::document::PdfDocument;
use crate::error::PdfiumError;
use crate::page::{PdfPoints, PdfRect};
use crate::page_annotation_objects::PdfPageAnnotationObjects;
use crate::page_object_form_fragment::PdfPageFormFragmentObject;
use crate::page_object_image::PdfPageImageObject;
use crate::page_object_path::PdfPagePathObject;
use crate::page_object_private::internal::PdfPageObjectPrivate;
use crate::page_object_shading::PdfPageShadingObject;
use crate::page_object_text::PdfPageTextObject;
use crate::page_object_unsupported::PdfPageUnsupportedObject;
use crate::page_objects::PdfPageObjects;
use std::convert::TryInto;
use std::os::raw::{c_int, c_uint};

/// The type of a single [PdfPageObject].
///
/// Note that Pdfium does not support or recognize all PDF page object types. For instance,
/// Pdfium does not currently support or recognize the External Object ("XObject") page object
/// type supported by Adobe Acrobat and Foxit's commercial PDF SDK. In these cases, Pdfium
/// will return [PdfPageObjectType::Unsupported].
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Eq, Hash)]
pub enum PdfPageObjectType {
    Unsupported = FPDF_PAGEOBJ_UNKNOWN as isize,
    Text = FPDF_PAGEOBJ_TEXT as isize,
    Path = FPDF_PAGEOBJ_PATH as isize,
    Image = FPDF_PAGEOBJ_IMAGE as isize,
    Shading = FPDF_PAGEOBJ_SHADING as isize,
    FormFragment = FPDF_PAGEOBJ_FORM as isize,
}

impl PdfPageObjectType {
    pub(crate) fn from_pdfium(value: u32) -> Result<PdfPageObjectType, PdfiumError> {
        match value {
            FPDF_PAGEOBJ_UNKNOWN => Ok(PdfPageObjectType::Unsupported),
            FPDF_PAGEOBJ_TEXT => Ok(PdfPageObjectType::Text),
            FPDF_PAGEOBJ_PATH => Ok(PdfPageObjectType::Path),
            FPDF_PAGEOBJ_IMAGE => Ok(PdfPageObjectType::Image),
            FPDF_PAGEOBJ_SHADING => Ok(PdfPageObjectType::Shading),
            FPDF_PAGEOBJ_FORM => Ok(PdfPageObjectType::FormFragment),
            _ => Err(PdfiumError::UnknownPdfPageObjectType),
        }
    }
}

/// The method used to combine overlapping colors when painting one [PdfPageObject] on top of
/// another.
///
/// The color being newly painted is the source color;the existing color being painted onto is the
/// backdrop color.
///
/// A formal definition of these blend modes can be found in Section 7.2.4 of
/// the PDF Reference Manual, version 1.7, on page 520.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PdfPageObjectBlendMode {
    /// Selects the source color, ignoring the backdrop.
    Normal,

    /// Multiplies the backdrop and source color values. The resulting color is always at least
    /// as dark as either of the two constituent colors. Multiplying any color with black
    /// produces black; multiplying with white leaves the original color unchanged.
    /// Painting successive overlapping objects with a color other than black or white
    /// produces progressively darker colors.
    Multiply,

    /// Multiplies the complements of the backdrop and source color values, then complements
    /// the result.

    /// The result color is always at least as light as either of the two constituent colors.
    /// Screening any color with white produces white; screening with black leaves the original
    /// color unchanged. The effect is similar to projecting multiple photographic slides
    /// simultaneously onto a single screen.
    Screen,

    /// Multiplies or screens the colors, depending on the backdrop color value. Source colors
    /// overlay the backdrop while preserving its highlights and shadows. The backdrop color is
    /// not replaced but is mixed with the source color to reflect the lightness or darkness of
    /// the backdrop.
    Overlay,

    /// Selects the darker of the backdrop and source colors. The backdrop is replaced with the
    /// source where the source is darker; otherwise, it is left unchanged.
    Darken,

    /// Selects the lighter of the backdrop and source colors. The backdrop is replaced with the
    /// source where the source is lighter; otherwise, it is left unchanged.
    Lighten,

    /// Brightens the backdrop color to reflect the source color. Painting with black produces no
    /// changes.
    ColorDodge,

    /// Darkens the backdrop color to reflect the source color. Painting with white produces no
    /// change.
    ColorBurn,

    /// Multiplies or screens the colors, depending on the source color value. The effect is similar
    /// to shining a harsh spotlight on the backdrop.
    HardLight,

    /// Darkens or lightens the colors, depending on the source color value. The effect is similar
    /// to shining a diffused spotlight on the backdrop.
    SoftLight,

    /// Subtracts the darker of the two constituent colors from the lighter color.
    /// Painting with white inverts the backdrop color; painting with black produces no change.
    Difference,

    /// Produces an effect similar to that of the Difference mode but lower in contrast.
    /// Painting with white inverts the backdrop color; painting with black produces no change.
    Exclusion,

    /// Preserves the luminosity of the backdrop color while adopting the hue and saturation
    /// of the source color.
    HSLColor,

    /// Preserves the luminosity and saturation of the backdrop color while adopting the hue
    /// of the source color.
    HSLHue,

    /// Preserves the hue and saturation of the backdrop color while adopting the luminosity
    /// of the source color.
    HSLLuminosity,

    /// Preserves the luminosity and hue of the backdrop color while adopting the saturation
    /// of the source color.
    HSLSaturation,
}

impl PdfPageObjectBlendMode {
    pub(crate) fn as_pdfium(&self) -> &str {
        match self {
            PdfPageObjectBlendMode::HSLColor => "Color",
            PdfPageObjectBlendMode::ColorBurn => "ColorBurn",
            PdfPageObjectBlendMode::ColorDodge => "ColorDodge",
            PdfPageObjectBlendMode::Darken => "Darken",
            PdfPageObjectBlendMode::Difference => "Difference",
            PdfPageObjectBlendMode::Exclusion => "Exclusion",
            PdfPageObjectBlendMode::HardLight => "HardLight",
            PdfPageObjectBlendMode::HSLHue => "Hue",
            PdfPageObjectBlendMode::Lighten => "Lighten",
            PdfPageObjectBlendMode::HSLLuminosity => "Luminosity",
            PdfPageObjectBlendMode::Multiply => "Multiply",
            PdfPageObjectBlendMode::Normal => "Normal",
            PdfPageObjectBlendMode::Overlay => "Overlay",
            PdfPageObjectBlendMode::HSLSaturation => "Saturation",
            PdfPageObjectBlendMode::Screen => "Screen",
            PdfPageObjectBlendMode::SoftLight => "SoftLight",
        }
    }
}

/// The shape that should be used at the corners of stroked paths.
///
/// Join styles are significant only at points where consecutive segments of a path
/// connect at an angle; segments that meet or intersect fortuitously receive no special treatment.
///
/// A formal definition of these styles can be found in Section 4.3.2 of
/// the PDF Reference Manual, version 1.7, on page 216.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PdfPageObjectLineJoin {
    /// The outer edges of the strokes for the two path segments are extended
    /// until they meet at an angle, as in a picture frame. If the segments meet at too
    /// sharp an angle, a bevel join is used instead.
    Miter = FPDF_LINEJOIN_MITER as isize,

    /// An arc of a circle with a diameter equal to the line width is drawn
    /// around the point where the two path segments meet, connecting the outer edges of
    /// the strokes for the two segments. This pie-slice-shaped figure is filled in,
    /// producing a rounded corner.
    Round = FPDF_LINEJOIN_ROUND as isize,

    /// The two path segments are finished with butt caps and the resulting notch
    /// beyond the ends of the segments is filled with a triangle.
    Bevel = FPDF_LINEJOIN_BEVEL as isize,
}

impl PdfPageObjectLineJoin {
    pub(crate) fn from_pdfium(value: c_int) -> Option<Self> {
        match value as u32 {
            FPDF_LINEJOIN_MITER => Some(Self::Miter),
            FPDF_LINEJOIN_ROUND => Some(Self::Round),
            FPDF_LINEJOIN_BEVEL => Some(Self::Bevel),
            _ => None,
        }
    }

    pub(crate) fn as_pdfium(&self) -> u32 {
        match self {
            PdfPageObjectLineJoin::Miter => FPDF_LINEJOIN_MITER,
            PdfPageObjectLineJoin::Round => FPDF_LINEJOIN_ROUND,
            PdfPageObjectLineJoin::Bevel => FPDF_LINEJOIN_BEVEL,
        }
    }
}

/// The shape that should be used at the ends of open stroked paths.
///
/// A formal definition of these styles can be found in Section 4.3.2 of
/// the PDF Reference Manual, version 1.7, on page 216.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PdfPageObjectLineCap {
    /// The stroke is squared off at the endpoint of the path. There is no
    /// projection beyond the end of the path.
    Butt = FPDF_LINECAP_BUTT as isize,

    /// A semicircular arc with a diameter equal to the line width is
    /// drawn around the endpoint and filled in.
    Round = FPDF_LINECAP_ROUND as isize,

    /// The stroke continues beyond the endpoint of the path
    /// for a distance equal to half the line width and is squared off.
    Square = FPDF_LINECAP_PROJECTING_SQUARE as isize,
}

impl PdfPageObjectLineCap {
    pub(crate) fn from_pdfium(value: c_int) -> Option<Self> {
        match value as u32 {
            FPDF_LINECAP_BUTT => Some(Self::Butt),
            FPDF_LINECAP_ROUND => Some(Self::Round),
            FPDF_LINECAP_PROJECTING_SQUARE => Some(Self::Square),
            _ => None,
        }
    }

    pub(crate) fn as_pdfium(&self) -> u32 {
        match self {
            PdfPageObjectLineCap::Butt => FPDF_LINECAP_BUTT,
            PdfPageObjectLineCap::Round => FPDF_LINECAP_ROUND,
            PdfPageObjectLineCap::Square => FPDF_LINECAP_PROJECTING_SQUARE,
        }
    }
}

/// A single object on a `PdfPage`.
pub enum PdfPageObject<'a> {
    Text(PdfPageTextObject<'a>),
    Path(PdfPagePathObject<'a>),
    Image(PdfPageImageObject<'a>),
    Shading(PdfPageShadingObject<'a>),
    FormFragment(PdfPageFormFragmentObject<'a>),

    /// Common properties shared by all [PdfPageObject] types can still be accessed for
    /// page objects not recognized by Pdfium, but object-specific functionality
    /// will be unavailable.
    Unsupported(PdfPageUnsupportedObject<'a>),
}

impl<'a> PdfPageObject<'a> {
    // Page objects can be attached either directly to a page or to an annotation.
    // We accommodate both possibilities.
    pub(crate) fn from_pdfium(
        object_handle: FPDF_PAGEOBJECT,
        page_handle: Option<FPDF_PAGE>,
        annotation_handle: Option<FPDF_ANNOTATION>,
        bindings: &'a dyn PdfiumLibraryBindings,
    ) -> Self {
        match PdfPageObjectType::from_pdfium(bindings.FPDFPageObj_GetType(object_handle) as u32)
            .unwrap_or(PdfPageObjectType::Unsupported)
        {
            PdfPageObjectType::Unsupported => {
                PdfPageObject::Unsupported(PdfPageUnsupportedObject::from_pdfium(
                    object_handle,
                    page_handle,
                    annotation_handle,
                    bindings,
                ))
            }
            PdfPageObjectType::Text => PdfPageObject::Text(PdfPageTextObject::from_pdfium(
                object_handle,
                page_handle,
                annotation_handle,
                bindings,
            )),
            PdfPageObjectType::Path => PdfPageObject::Path(PdfPagePathObject::from_pdfium(
                object_handle,
                page_handle,
                annotation_handle,
                bindings,
            )),
            PdfPageObjectType::Image => PdfPageObject::Image(PdfPageImageObject::from_pdfium(
                object_handle,
                page_handle,
                annotation_handle,
                bindings,
            )),
            PdfPageObjectType::Shading => {
                PdfPageObject::Shading(PdfPageShadingObject::from_pdfium(
                    object_handle,
                    page_handle,
                    annotation_handle,
                    bindings,
                ))
            }
            PdfPageObjectType::FormFragment => {
                PdfPageObject::FormFragment(PdfPageFormFragmentObject::from_pdfium(
                    object_handle,
                    page_handle,
                    annotation_handle,
                    bindings,
                ))
            }
        }
    }

    #[inline]
    pub(crate) fn unwrap_as_trait(&self) -> &dyn PdfPageObjectPrivate<'a> {
        match self {
            PdfPageObject::Text(object) => object,
            PdfPageObject::Path(object) => object,
            PdfPageObject::Image(object) => object,
            PdfPageObject::Shading(object) => object,
            PdfPageObject::FormFragment(object) => object,
            PdfPageObject::Unsupported(object) => object,
        }
    }

    #[inline]
    pub(crate) fn unwrap_as_trait_mut(&mut self) -> &mut dyn PdfPageObjectPrivate<'a> {
        match self {
            PdfPageObject::Text(object) => object,
            PdfPageObject::Path(object) => object,
            PdfPageObject::Image(object) => object,
            PdfPageObject::Shading(object) => object,
            PdfPageObject::FormFragment(object) => object,
            PdfPageObject::Unsupported(object) => object,
        }
    }

    /// The object type of this [PdfPageObject].
    ///
    /// Note that Pdfium does not support or recognize all PDF page object types. For instance,
    /// Pdfium does not currently support or recognize the External Object ("XObject") page object
    /// type supported by Adobe Acrobat and Foxit's commercial PDF SDK. In these cases, Pdfium
    /// will return `PdfPageObjectType::Unsupported`.
    #[inline]
    pub fn object_type(&self) -> PdfPageObjectType {
        match self {
            PdfPageObject::Text(_) => PdfPageObjectType::Text,
            PdfPageObject::Path(_) => PdfPageObjectType::Path,
            PdfPageObject::Image(_) => PdfPageObjectType::Image,
            PdfPageObject::Shading(_) => PdfPageObjectType::Shading,
            PdfPageObject::FormFragment(_) => PdfPageObjectType::FormFragment,
            PdfPageObject::Unsupported(_) => PdfPageObjectType::Unsupported,
        }
    }

    /// Returns `true` if this [PdfPageObject] has an object type other than [PdfPageObjectType::Unsupported].
    ///
    /// The [PdfPageObject::as_text_object()], [PdfPageObject::as_path_object()], [PdfPageObject::as_image_object()],
    /// [PdfPageObject::as_shading_object()], and [PdfPageObject::as_form_fragment_object()] functions
    /// can be used to access properties and functions pertaining to a specific page object type.
    #[inline]
    pub fn is_supported(&self) -> bool {
        !self.is_unsupported()
    }

    /// Returns `true` if this [PdfPageObject] has an object type of [PdfPageObjectType::Unsupported].
    ///
    /// Common properties shared by all [PdfPageObject] types can still be accessed for
    /// page objects not recognized by Pdfium, but object-specific functionality
    /// will be unavailable.
    #[inline]
    pub fn is_unsupported(&self) -> bool {
        self.object_type() == PdfPageObjectType::Unsupported
    }

    /// Returns an immutable reference to the underlying [PdfPageTextObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Text].
    #[inline]
    pub fn as_text_object(&self) -> Option<&PdfPageTextObject> {
        match self {
            PdfPageObject::Text(object) => Some(object),
            _ => None,
        }
    }

    /// Returns a mutable reference to the underlying [PdfPageTextObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Text].
    #[inline]
    pub fn as_text_object_mut(&mut self) -> Option<&mut PdfPageTextObject<'a>> {
        match self {
            PdfPageObject::Text(object) => Some(object),
            _ => None,
        }
    }

    /// Returns an immutable reference to the underlying [PdfPagePathObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Path].
    #[inline]
    pub fn as_path_object(&self) -> Option<&PdfPagePathObject> {
        match self {
            PdfPageObject::Path(object) => Some(object),
            _ => None,
        }
    }

    /// Returns a mutable reference to the underlying [PdfPagePathObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Path].
    #[inline]
    pub fn as_path_object_mut(&mut self) -> Option<&mut PdfPagePathObject<'a>> {
        match self {
            PdfPageObject::Path(object) => Some(object),
            _ => None,
        }
    }

    /// Returns an immutable reference to the underlying [PdfPageImageObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Image].
    #[inline]
    pub fn as_image_object(&self) -> Option<&PdfPageImageObject> {
        match self {
            PdfPageObject::Image(object) => Some(object),
            _ => None,
        }
    }

    /// Returns a mutable reference to the underlying [PdfPageImageObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Image].
    #[inline]
    pub fn as_image_object_mut(&mut self) -> Option<&mut PdfPageImageObject<'a>> {
        match self {
            PdfPageObject::Image(object) => Some(object),
            _ => None,
        }
    }

    /// Returns an immutable reference to the underlying [PdfPageShadingObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Shading].
    #[inline]
    pub fn as_shading_object(&self) -> Option<&PdfPageShadingObject> {
        match self {
            PdfPageObject::Shading(object) => Some(object),
            _ => None,
        }
    }

    /// Returns a mutable reference to the underlying [PdfPageShadingObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::Shading].
    #[inline]
    pub fn as_shading_object_mut(&mut self) -> Option<&mut PdfPageShadingObject<'a>> {
        match self {
            PdfPageObject::Shading(object) => Some(object),
            _ => None,
        }
    }

    /// Returns an immutable reference to the underlying [PdfPageFormFragmentObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::FormFragment].
    #[inline]
    pub fn as_form_fragment_object(&self) -> Option<&PdfPageFormFragmentObject> {
        match self {
            PdfPageObject::FormFragment(object) => Some(object),
            _ => None,
        }
    }

    /// Returns a mutable reference to the underlying [PdfPageFormFragmentObject] for this [PdfPageObject],
    /// if this page object has an object type of [PdfPageObjectType::FormFragment].
    #[inline]
    pub fn as_form_fragment_object_mut(&mut self) -> Option<&mut PdfPageFormFragmentObject<'a>> {
        match self {
            PdfPageObject::FormFragment(object) => Some(object),
            _ => None,
        }
    }
}

/// Functionality common to all [PdfPageObject] objects, regardless of their [PdfPageObjectType].
pub trait PdfPageObjectCommon<'a> {
    /// Returns `true` if this [PdfPageObject] contains transparency.
    fn has_transparency(&self) -> bool;

    /// Returns the bounding box of this [PdfPageObject].
    ///
    /// For text objects, the bottom of the bounding box is set to the font baseline. Any characters
    /// in the text object that have glyph shapes that descends below the font baseline will extend
    /// beneath the bottom of this bounding box. To measure the distance of the maximum descent of
    /// any glyphs, use the [PdfPageTextObject::descent()] function.
    fn bounds(&self) -> Result<PdfRect, PdfiumError>;

    /// Returns the width of this [PdfPageObject].
    #[inline]
    fn width(&self) -> Result<PdfPoints, PdfiumError> {
        Ok(self.bounds()?.width())
    }

    /// Returns the height of this [PdfPageObject].
    #[inline]
    fn height(&self) -> Result<PdfPoints, PdfiumError> {
        Ok(self.bounds()?.height())
    }

    /// Returns `true` if the bounds of this [PdfPageObject] lie entirely within the given rectangle.
    #[inline]
    fn is_inside_rect(&self, rect: &PdfRect) -> bool {
        self.bounds()
            .map(|bounds| bounds.is_inside(rect))
            .unwrap_or(false)
    }

    /// Returns `true` if the bounds of this [PdfPageObject] lie at least partially within
    /// the given rectangle.
    #[inline]
    fn does_overlap_rect(&self, rect: &PdfRect) -> bool {
        self.bounds()
            .map(|bounds| bounds.does_overlap(rect))
            .unwrap_or(false)
    }

    /// Applies the given transformation, expressed as six values representing the six configurable
    /// elements of a nine-element 3x3 PDF transformation matrix, to this [PdfPageObject].
    ///
    /// To move, scale, rotate, or skew a [PdfPageObject], consider using one or more of the
    /// following functions. Internally they all use [PdfPageObjectCommon::transform()], but are
    /// probably easier to use (and certainly clearer in their intent) in most situations.
    ///
    /// * [PdfPageObjectCommon::translate()]: changes the position of a [PdfPageObject].
    /// * [PdfPageObjectCommon::scale()]: changes the size of a [PdfPageObject].
    /// * [PdfPageObjectCommon::rotate_clockwise_degrees()], [PdfPageObjectCommon::rotate_counter_clockwise_degrees()],
    /// [PdfPageObjectCommon::rotate_clockwise_radians()], [PdfPageObjectCommon::rotate_counter_clockwise_radians()]:
    /// rotates a [PdfPageObject] around its origin.
    /// * [PdfPageObjectCommon::skew_degrees()], [PdfPageObjectCommon::skew_radians()]: skews a [PdfPageObject]
    /// relative to its axes.
    ///
    /// **The order in which transformations are applied is significant.**
    /// For example, the result of rotating _then_ translating a page object may be vastly different
    /// from translating _then_ rotating the same page object. In general, to obtain the expected
    /// results, transformations should be performed in the following order:
    /// * Scale and/or skew
    /// * Rotate
    /// * Translate
    ///
    /// An overview of PDF transformation matrices can be found in the PDF Reference Manual
    /// version 1.7 on page 204; a detailed description can be founded in section 4.2.3 on page 207.
    fn transform(
        &mut self,
        a: f64,
        b: f64,
        c: f64,
        d: f64,
        e: f64,
        f: f64,
    ) -> Result<(), PdfiumError>;

    /// Transforms this [PdfPageObject] by applying the transformation matrix read from the given [PdfPageObject].
    ///
    /// Any translation, rotation, scaling, or skewing transformations currently applied to the
    /// given [PdfPageObject] will be immediately applied to this [PdfPageObject].
    fn transform_from(&mut self, other: &PdfPageObject) -> Result<(), PdfiumError>;

    /// Moves the origin of this [PdfPageObject] by the given horizontal and vertical delta distances.
    #[inline]
    fn translate(&mut self, delta_x: PdfPoints, delta_y: PdfPoints) -> Result<(), PdfiumError> {
        self.transform(
            1.0,
            0.0,
            0.0,
            1.0,
            delta_x.value as f64,
            delta_y.value as f64,
        )
    }

    /// Returns the current horizontal and vertical translation of the origin of this [PdfPageObject].
    #[inline]
    fn get_translation(&self) -> (PdfPoints, PdfPoints) {
        (
            self.get_horizontal_translation(),
            self.get_vertical_translation(),
        )
    }

    /// Returns the current horizontal translation of the origin of this [PdfPageObject].
    fn get_horizontal_translation(&self) -> PdfPoints;

    /// Returns the current vertical translation of the origin of this [PdfPageObject].
    fn get_vertical_translation(&self) -> PdfPoints;

    /// Changes the size of this [PdfPageObject], scaling it by the given horizontal and
    /// vertical scale factors.
    #[inline]
    fn scale(
        &mut self,
        horizontal_scale_factor: f64,
        vertical_scale_factor: f64,
    ) -> Result<(), PdfiumError> {
        self.transform(
            horizontal_scale_factor,
            0.0,
            0.0,
            vertical_scale_factor,
            0.0,
            0.0,
        )
    }

    /// Flips this [PdfPageObject] horizontally around its origin by applying a horizontal scale factor of -1.
    #[inline]
    fn flip_horizontally(&mut self) -> Result<(), PdfiumError> {
        self.scale(-1.0, 1.0)
    }

    /// Flips this [PdfPageObject] vertically around its origin by applying a vertical scale factor of -1.
    #[inline]
    fn flip_vertically(&mut self) -> Result<(), PdfiumError> {
        self.scale(1.0, -1.0)
    }

    /// Reflects this [PdfPageObject] by flipping it both horizontally and vertically around its origin.
    #[inline]
    fn reflect(&mut self) -> Result<(), PdfiumError> {
        self.scale(-1.0, -1.0)
    }

    /// Returns the current horizontal and vertical scale factors applied to this [PdfPageObject].
    #[inline]
    fn get_scale(&self) -> (f64, f64) {
        (self.get_horizontal_scale(), self.get_vertical_scale())
    }

    /// Returns the current horizontal scale factor applied to this [PdfPageObject].
    fn get_horizontal_scale(&self) -> f64;

    /// Returns the current vertical scale factor applied to this [PdfPageObject].
    fn get_vertical_scale(&self) -> f64;

    /// Rotates this [PdfPageObject] counter-clockwise by the given number of degrees.
    #[inline]
    fn rotate_counter_clockwise_degrees(&mut self, degrees: f32) -> Result<(), PdfiumError> {
        self.rotate_counter_clockwise_radians(degrees.to_radians())
    }

    /// Returns the counter-clockwise rotation applied to this [PdfPageObject], in degrees.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_rotation_counter_clockwise_degrees(&self) -> f32 {
        self.get_rotation_counter_clockwise_radians().to_degrees()
    }

    /// Rotates this [PdfPageObject] clockwise by the given number of degrees.
    #[inline]
    fn rotate_clockwise_degrees(&mut self, degrees: f32) -> Result<(), PdfiumError> {
        self.rotate_counter_clockwise_degrees(-degrees)
    }

    /// Returns the clockwise rotation applied to this [PdfPageObject], in degrees.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_rotation_clockwise_degrees(&self) -> f32 {
        -self.get_rotation_counter_clockwise_degrees()
    }

    /// Rotates this [PdfPageObject] counter-clockwise by the given number of radians.
    #[inline]
    fn rotate_counter_clockwise_radians(&mut self, radians: f32) -> Result<(), PdfiumError> {
        let cos_theta = radians.cos() as f64;

        let sin_theta = radians.sin() as f64;

        self.transform(cos_theta, sin_theta, -sin_theta, cos_theta, 0.0, 0.0)
    }

    /// Returns the counter-clockwise rotation applied to this [PdfPageObject], in radians.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    fn get_rotation_counter_clockwise_radians(&self) -> f32;

    /// Rotates this [PdfPageObject] clockwise by the given number of radians.
    #[inline]
    fn rotate_clockwise_radians(&mut self, radians: f32) -> Result<(), PdfiumError> {
        self.rotate_counter_clockwise_radians(-radians)
    }

    /// Returns the clockwise rotation applied to this [PdfPageObject], in radians.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_rotation_clockwise_radians(&self) -> f32 {
        -self.get_rotation_counter_clockwise_radians()
    }

    /// Skews the axes of this [PdfPageObject] by the given angles in degrees.
    #[inline]
    fn skew_degrees(&mut self, x_axis_skew: f32, y_axis_skew: f32) -> Result<(), PdfiumError> {
        self.skew_radians(x_axis_skew.to_radians(), y_axis_skew.to_radians())
    }

    /// Returns the current x axis and y axis skew angles applied to this [PdfPageObject], in degrees.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_skew_degrees(&self) -> (f32, f32) {
        (
            self.get_x_axis_skew_degrees(),
            self.get_y_axis_skew_degrees(),
        )
    }

    /// Returns the current x axis skew angle applied to this [PdfPageObject], in degrees.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_x_axis_skew_degrees(&self) -> f32 {
        self.get_x_axis_skew_radians().to_degrees()
    }

    /// Returns the current y axis skew applied to this [PdfPageObject], in degrees.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_y_axis_skew_degrees(&self) -> f32 {
        self.get_y_axis_skew_radians().to_degrees()
    }

    /// Skews the axes of this [PdfPageObject] by the given angles in radians.
    #[inline]
    fn skew_radians(&mut self, x_axis_skew: f32, y_axis_skew: f32) -> Result<(), PdfiumError> {
        let tan_alpha = x_axis_skew.tan() as f64;

        let tan_beta = y_axis_skew.tan() as f64;

        self.transform(1.0, tan_alpha, tan_beta, 1.0, 0.0, 0.0)
    }

    /// Returns the current x axis and y axis skew angles applied to this [PdfPageObject], in radians.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    #[inline]
    fn get_skew_radians(&self) -> (f32, f32) {
        (
            self.get_x_axis_skew_radians(),
            self.get_y_axis_skew_radians(),
        )
    }

    /// Returns the current x axis skew applied to this [PdfPageObject], in radians.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    fn get_x_axis_skew_radians(&self) -> f32;

    /// Returns the current y axis skew applied to this [PdfPageObject], in radians.
    ///
    /// If the object is both rotated and skewed, the return value of this function will reflect
    /// the combined operation.
    fn get_y_axis_skew_radians(&self) -> f32;

    /// Sets the blend mode that will be applied when painting this [PdfPageObject].
    ///
    /// Note that Pdfium does not currently expose a function to read the currently set blend mode.
    fn set_blend_mode(&mut self, blend_mode: PdfPageObjectBlendMode) -> Result<(), PdfiumError>;

    /// Returns the color of any filled paths in this [PdfPageObject].
    fn fill_color(&self) -> Result<PdfColor, PdfiumError>;

    /// Sets the color of any filled paths in this [PdfPageObject].
    fn set_fill_color(&mut self, fill_color: PdfColor) -> Result<(), PdfiumError>;

    /// Returns the color of any stroked lines in this [PdfPageObject].
    fn stroke_color(&self) -> Result<PdfColor, PdfiumError>;

    /// Sets the color of any stroked lines in this [PdfPageObject].
    ///
    /// Even if this object's path is set with a visible color and a non-zero stroke width,
    /// the object's stroke mode must be set in order for strokes to actually be visible.
    fn set_stroke_color(&mut self, stroke_color: PdfColor) -> Result<(), PdfiumError>;

    /// Returns the width of any stroked lines in this [PdfPageObject].
    fn stroke_width(&self) -> Result<PdfPoints, PdfiumError>;

    /// Sets the width of any stroked lines in this [PdfPageObject].
    ///
    /// A line width of 0 denotes the thinnest line that can be rendered at device resolution:
    /// 1 device pixel wide. However, some devices cannot reproduce 1-pixel lines,
    /// and on high-resolution devices, they are nearly invisible. Since the results of rendering
    /// such zero-width lines are device-dependent, their use is not recommended.
    ///
    /// Even if this object's path is set with a visible color and a non-zero stroke width,
    /// the object's stroke mode must be set in order for strokes to actually be visible.
    fn set_stroke_width(&mut self, stroke_width: PdfPoints) -> Result<(), PdfiumError>;

    /// Returns the line join style that will be used when painting stroked path segments
    /// in this [PdfPageObject].
    fn line_join(&self) -> Result<PdfPageObjectLineJoin, PdfiumError>;

    /// Sets the line join style that will be used when painting stroked path segments
    /// in this [PdfPageObject].
    fn set_line_join(&mut self, line_join: PdfPageObjectLineJoin) -> Result<(), PdfiumError>;

    /// Returns the line cap style that will be used when painting stroked path segments
    /// in this [PdfPageObject].
    fn line_cap(&self) -> Result<PdfPageObjectLineCap, PdfiumError>;

    /// Sets the line cap style that will be used when painting stroked path segments
    /// in this [PdfPageObject].
    fn set_line_cap(&mut self, line_cap: PdfPageObjectLineCap) -> Result<(), PdfiumError>;

    /// Returns `true` if this [PdfPageObject] can be successfully copied by calling its
    /// `try_copy()` function.
    ///
    /// Not all page objects can be successfully copied. The following restrictions apply:
    ///
    /// * For path objects, it is not possible to copy a path object that contains a Bézier path
    /// segment, because Pdfium does not currently provide any way to retrieve the control points of a
    /// Bézier curve of an existing path object.
    /// * For text objects, the font used by the object must be present in the destination document,
    /// or text rendering behaviour will be unpredictable. While text objects refer to fonts,
    /// font data is embedded into documents separately from text objects.
    /// * For image objects, Pdfium allows iterating over the list of image filters applied
    /// to an image object, but currently provides no way to set a new object's image filters.
    /// As a result, it is not possible to copy an image object that has any image filters applied.
    ///
    /// Pdfium currently allows setting the blend mode for a page object, but provides no way
    /// to retrieve an object's current blend mode. As a result, the blend mode setting of the
    /// original object will not be transferred to the copy.
    fn is_copyable(&self) -> bool;

    /// Attempts to copy this [PdfPageObject] by creating a new page object and copying across
    /// all the properties of this [PdfPageObject] to the new page object.
    ///
    /// Not all page objects can be successfully copied. The following restrictions apply:
    ///
    /// * For path objects, it is not possible to copy a path object that contains a Bézier path
    /// segment, because Pdfium does not currently provide any way to retrieve the control points of a
    /// Bézier curve of an existing path object.
    /// * For text objects, the font used by the object must be present in the destination document,
    /// or text rendering behaviour will be unpredictable. While text objects refer to fonts,
    /// font data is embedded into documents separately from text objects.
    /// * For image objects, Pdfium allows iterating over the list of image filters applied
    /// to an image object, but currently provides no way to set a new object's image filters.
    /// As a result, it is not possible to copy an image object that has any image filters applied.
    ///
    /// Pdfium currently allows setting the blend mode for a page object, but provides no way
    /// to retrieve an object's current blend mode. As a result, the blend mode setting of the
    /// original object will not be transferred to the copy.
    ///
    /// The returned page object will be detached from any existing `PdfPage`. Its lifetime
    /// will be bound to the lifetime of the given destination [PdfDocument].
    fn try_copy<'b>(&self, document: &PdfDocument<'b>) -> Result<PdfPageObject<'b>, PdfiumError>;
}

// Blanket implementation for all PdfPageObject types.

impl<'a, T> PdfPageObjectCommon<'a> for T
where
    T: PdfPageObjectPrivate<'a>,
{
    #[inline]
    fn has_transparency(&self) -> bool {
        self.has_transparency_impl()
    }

    #[inline]
    fn bounds(&self) -> Result<PdfRect, PdfiumError> {
        self.bounds_impl()
    }

    #[inline]
    fn transform(
        &mut self,
        a: f64,
        b: f64,
        c: f64,
        d: f64,
        e: f64,
        f: f64,
    ) -> Result<(), PdfiumError> {
        self.transform_impl(a, b, c, d, e, f)
    }

    #[inline]
    fn transform_from(&mut self, other: &PdfPageObject) -> Result<(), PdfiumError> {
        self.set_matrix(other.matrix()?)
    }

    #[inline]
    fn get_horizontal_translation(&self) -> PdfPoints {
        self.get_horizontal_translation_impl()
    }

    #[inline]
    fn get_vertical_translation(&self) -> PdfPoints {
        self.get_vertical_translation_impl()
    }

    #[inline]
    fn get_horizontal_scale(&self) -> f64 {
        self.get_horizontal_scale_impl()
    }

    #[inline]
    fn get_vertical_scale(&self) -> f64 {
        self.get_vertical_scale_impl()
    }

    fn get_rotation_counter_clockwise_radians(&self) -> f32 {
        self.get_rotation_counter_clockwise_radians_impl()
    }

    #[inline]
    fn get_x_axis_skew_radians(&self) -> f32 {
        self.get_x_axis_skew_radians_impl()
    }

    #[inline]
    fn get_y_axis_skew_radians(&self) -> f32 {
        self.get_y_axis_skew_radians_impl()
    }

    #[inline]
    fn set_blend_mode(&mut self, blend_mode: PdfPageObjectBlendMode) -> Result<(), PdfiumError> {
        self.bindings()
            .FPDFPageObj_SetBlendMode(*self.get_object_handle(), blend_mode.as_pdfium());

        match self.bindings().get_pdfium_last_error() {
            Some(err) => Err(PdfiumError::PdfiumLibraryInternalError(err)),
            None => Ok(()),
        }
    }

    #[inline]
    fn fill_color(&self) -> Result<PdfColor, PdfiumError> {
        let mut r = 0;

        let mut g = 0;

        let mut b = 0;

        let mut a = 0;

        if self
            .bindings()
            .is_true(self.bindings().FPDFPageObj_GetFillColor(
                *self.get_object_handle(),
                &mut r,
                &mut g,
                &mut b,
                &mut a,
            ))
        {
            Ok(PdfColor::new(
                r.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
                g.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
                b.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
                a.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
            ))
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn set_fill_color(&mut self, fill_color: PdfColor) -> Result<(), PdfiumError> {
        if self
            .bindings()
            .is_true(self.bindings().FPDFPageObj_SetFillColor(
                *self.get_object_handle(),
                fill_color.red() as c_uint,
                fill_color.green() as c_uint,
                fill_color.blue() as c_uint,
                fill_color.alpha() as c_uint,
            ))
        {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn stroke_color(&self) -> Result<PdfColor, PdfiumError> {
        let mut r = 0;

        let mut g = 0;

        let mut b = 0;

        let mut a = 0;

        if self
            .bindings()
            .is_true(self.bindings().FPDFPageObj_GetStrokeColor(
                *self.get_object_handle(),
                &mut r,
                &mut g,
                &mut b,
                &mut a,
            ))
        {
            Ok(PdfColor::new(
                r.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
                g.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
                b.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
                a.try_into()
                    .map_err(PdfiumError::UnableToConvertPdfiumColorValueToRustu8)?,
            ))
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn set_stroke_color(&mut self, stroke_color: PdfColor) -> Result<(), PdfiumError> {
        if self
            .bindings()
            .is_true(self.bindings().FPDFPageObj_SetStrokeColor(
                *self.get_object_handle(),
                stroke_color.red() as c_uint,
                stroke_color.green() as c_uint,
                stroke_color.blue() as c_uint,
                stroke_color.alpha() as c_uint,
            ))
        {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn stroke_width(&self) -> Result<PdfPoints, PdfiumError> {
        let mut width = 0.0;

        if self.bindings().is_true(
            self.bindings()
                .FPDFPageObj_GetStrokeWidth(*self.get_object_handle(), &mut width),
        ) {
            Ok(PdfPoints::new(width))
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn set_stroke_width(&mut self, stroke_width: PdfPoints) -> Result<(), PdfiumError> {
        if self.bindings().is_true(
            self.bindings()
                .FPDFPageObj_SetStrokeWidth(*self.get_object_handle(), stroke_width.value),
        ) {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn line_join(&self) -> Result<PdfPageObjectLineJoin, PdfiumError> {
        PdfPageObjectLineJoin::from_pdfium(
            self.bindings()
                .FPDFPageObj_GetLineJoin(*self.get_object_handle()),
        )
        .ok_or(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
    }

    #[inline]
    fn set_line_join(&mut self, line_join: PdfPageObjectLineJoin) -> Result<(), PdfiumError> {
        if self.bindings().is_true(
            self.bindings()
                .FPDFPageObj_SetLineJoin(*self.get_object_handle(), line_join.as_pdfium() as c_int),
        ) {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn line_cap(&self) -> Result<PdfPageObjectLineCap, PdfiumError> {
        PdfPageObjectLineCap::from_pdfium(
            self.bindings()
                .FPDFPageObj_GetLineCap(*self.get_object_handle()),
        )
        .ok_or(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
    }

    #[inline]
    fn set_line_cap(&mut self, line_cap: PdfPageObjectLineCap) -> Result<(), PdfiumError> {
        if self.bindings().is_true(
            self.bindings()
                .FPDFPageObj_SetLineCap(*self.get_object_handle(), line_cap.as_pdfium() as c_int),
        ) {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumFunctionReturnValueIndicatedFailure)
        }
    }

    #[inline]
    fn is_copyable(&self) -> bool {
        self.is_cloneable_impl()
    }

    #[inline]
    fn try_copy<'b>(&self, document: &PdfDocument<'b>) -> Result<PdfPageObject<'b>, PdfiumError> {
        self.try_clone_impl(document)
    }
}

impl<'a> PdfPageObjectPrivate<'a> for PdfPageObject<'a> {
    #[inline]
    fn get_object_handle(&self) -> &FPDF_PAGEOBJECT {
        self.unwrap_as_trait().get_object_handle()
    }

    #[inline]
    fn get_page_handle(&self) -> &Option<FPDF_PAGE> {
        self.unwrap_as_trait().get_page_handle()
    }

    #[inline]
    fn set_page_handle(&mut self, page: FPDF_PAGE) {
        self.unwrap_as_trait_mut().set_page_handle(page);
    }

    #[inline]
    fn clear_page_handle(&mut self) {
        self.unwrap_as_trait_mut().clear_page_handle();
    }

    #[inline]
    fn get_annotation_handle(&self) -> &Option<FPDF_ANNOTATION> {
        self.unwrap_as_trait().get_annotation_handle()
    }

    #[inline]
    fn set_annotation_handle(&mut self, annotation: FPDF_ANNOTATION) {
        self.unwrap_as_trait_mut().set_annotation_handle(annotation);
    }

    #[inline]
    fn clear_annotation_handle(&mut self) {
        self.unwrap_as_trait_mut().clear_annotation_handle();
    }

    #[inline]
    fn bindings(&self) -> &dyn PdfiumLibraryBindings {
        self.unwrap_as_trait().bindings()
    }

    #[inline]
    fn is_object_memory_owned_by_container(&self) -> bool {
        self.unwrap_as_trait().is_object_memory_owned_by_container()
    }

    #[inline]
    fn add_object_to_page(&mut self, page_objects: &PdfPageObjects) -> Result<(), PdfiumError> {
        self.unwrap_as_trait_mut().add_object_to_page(page_objects)
    }

    #[inline]
    fn remove_object_from_page(&mut self) -> Result<(), PdfiumError> {
        self.unwrap_as_trait_mut().remove_object_from_page()
    }

    #[inline]
    fn add_object_to_annotation(
        &mut self,
        annotation_objects: &PdfPageAnnotationObjects,
    ) -> Result<(), PdfiumError> {
        self.unwrap_as_trait_mut()
            .add_object_to_annotation(annotation_objects)
    }

    #[inline]
    fn remove_object_from_annotation(&mut self) -> Result<(), PdfiumError> {
        self.unwrap_as_trait_mut().remove_object_from_annotation()
    }

    #[inline]
    fn is_cloneable_impl(&self) -> bool {
        self.unwrap_as_trait().is_cloneable_impl()
    }

    #[inline]
    fn try_clone_impl<'b>(
        &self,
        document: &PdfDocument<'b>,
    ) -> Result<PdfPageObject<'b>, PdfiumError> {
        self.unwrap_as_trait().try_copy(document)
    }
}

impl<'a> From<PdfPageFormFragmentObject<'a>> for PdfPageObject<'a> {
    #[inline]
    fn from(object: PdfPageFormFragmentObject<'a>) -> Self {
        Self::FormFragment(object)
    }
}

impl<'a> From<PdfPageImageObject<'a>> for PdfPageObject<'a> {
    #[inline]
    fn from(object: PdfPageImageObject<'a>) -> Self {
        Self::Image(object)
    }
}

impl<'a> From<PdfPagePathObject<'a>> for PdfPageObject<'a> {
    #[inline]
    fn from(object: PdfPagePathObject<'a>) -> Self {
        Self::Path(object)
    }
}

impl<'a> From<PdfPageShadingObject<'a>> for PdfPageObject<'a> {
    #[inline]
    fn from(object: PdfPageShadingObject<'a>) -> Self {
        Self::Shading(object)
    }
}

impl<'a> From<PdfPageTextObject<'a>> for PdfPageObject<'a> {
    #[inline]
    fn from(object: PdfPageTextObject<'a>) -> Self {
        Self::Text(object)
    }
}

impl<'a> From<PdfPageUnsupportedObject<'a>> for PdfPageObject<'a> {
    #[inline]
    fn from(object: PdfPageUnsupportedObject<'a>) -> Self {
        Self::Unsupported(object)
    }
}

impl<'a> Drop for PdfPageObject<'a> {
    /// Closes this [PdfPageObject], releasing held memory.
    #[inline]
    fn drop(&mut self) {
        // The documentation for FPDFPageObj_Destroy() states that we only need
        // call the function for page objects created by FPDFPageObj_CreateNew*() or
        // FPDFPageObj_New*Obj() _and_ where the newly-created object was _not_ subsequently
        // added to a PdfPage or PdfPageAnnotation via a call to FPDFPage_InsertObject() or
        // FPDFAnnot_AppendObject().

        // In other words, retrieving a page object that already exists in a document evidently
        // does not allocate any additional resources, so we don't need to free anything.
        // (Indeed, if we try to, Pdfium segfaults.)

        if !self.is_object_memory_owned_by_container() {
            self.bindings()
                .FPDFPageObj_Destroy(*self.get_object_handle());
        }
    }
}