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
//! Defines the [PdfPagePathObject] struct, exposing functionality related to a single
//! page object defining a path.

use crate::bindgen::{
    FPDF_ANNOTATION, FPDF_BOOL, FPDF_FILLMODE_ALTERNATE, FPDF_FILLMODE_NONE, FPDF_FILLMODE_WINDING,
    FPDF_PAGE, FPDF_PAGEOBJECT,
};
use crate::bindings::PdfiumLibraryBindings;
use crate::color::PdfColor;
use crate::error::{PdfiumError, PdfiumInternalError};
use crate::page::{PdfPoints, PdfRect};
use crate::page_object::{PdfPageObject, PdfPageObjectCommon};
use crate::page_object_private::internal::PdfPageObjectPrivate;
use crate::path_segment::{PdfPathSegment, PdfPathSegmentType};
use crate::path_segments::{PdfPathSegmentIndex, PdfPathSegments, PdfPathSegmentsIterator};
use crate::prelude::PdfDocument;
use std::convert::TryInto;
use std::os::raw::{c_int, c_uint};

/// Sets the method used to determine the path region to fill.
///
/// The default fill mode used by `pdfium-render` when creating new [PdfPagePathObject]
/// instances is [PdfPathFillMode::Winding]. The fill mode can be changed on an
/// object-by-object basis by calling the [PdfPagePathObject::set_fill_and_stroke_mode()] function.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PdfPathFillMode {
    /// The path will not be filled.
    None = FPDF_FILLMODE_NONE as isize,

    /// The even-odd rule will be used to determine the path region to fill.
    ///
    /// The even-odd rule determines whether a point is inside a path by drawing a ray from that
    /// point in any direction and simply counting the number of path segments that cross the
    /// ray, regardless of direction. If this number is odd, the point is inside; if even, the
    /// point is outside. This yields the same results as the nonzero winding number rule
    /// for paths with simple shapes, but produces different results for more complex shapes.
    ///
    /// More information, including visual examples, can be found in Section 4.4.2 of
    /// the PDF Reference Manual, version 1.7, on page 233.
    EvenOdd = FPDF_FILLMODE_ALTERNATE as isize,

    /// The non-zero winding number rule will be used to determine the path region to fill.
    ///
    /// The nonzero winding number rule determines whether a given point is inside a
    /// path by conceptually drawing a ray from that point to infinity in any direction
    /// and then examining the places where a segment of the path crosses the ray. Start-
    /// ing with a count of 0, the rule adds 1 each time a path segment crosses the ray
    /// from left to right and subtracts 1 each time a segment crosses from right to left.
    /// After counting all the crossings, if the result is 0, the point is outside the path;
    /// otherwise, it is inside.
    ///
    /// This is the default fill mode used by `pdfium-render` when creating new [PdfPagePathObject]
    /// instances. The fill mode can be changed on an object-by-object basis by calling the
    /// [PdfPagePathObject::set_fill_and_stroke_mode()] function.
    ///
    /// More information, including visual examples, can be found in Section 4.4.2 of
    /// the PDF Reference Manual, version 1.7, on page 232.
    Winding = FPDF_FILLMODE_WINDING as isize,
}

impl PdfPathFillMode {
    #[inline]
    pub(crate) fn from_pdfium(value: c_int) -> Result<PdfPathFillMode, PdfiumError> {
        match value as u32 {
            FPDF_FILLMODE_NONE => Ok(PdfPathFillMode::None),
            FPDF_FILLMODE_ALTERNATE => Ok(PdfPathFillMode::EvenOdd),
            FPDF_FILLMODE_WINDING => Ok(PdfPathFillMode::Winding),
            _ => Err(PdfiumError::UnknownPdfPagePathFillMode),
        }
    }

    #[inline]
    #[allow(dead_code)]
    // The as_pdfium() function is not currently used, but we expect it to be in future
    pub(crate) fn as_pdfium(&self) -> c_uint {
        match self {
            PdfPathFillMode::None => FPDF_FILLMODE_NONE,
            PdfPathFillMode::EvenOdd => FPDF_FILLMODE_ALTERNATE,
            PdfPathFillMode::Winding => FPDF_FILLMODE_WINDING,
        }
    }
}

impl Default for PdfPathFillMode {
    /// Returns the default fill mode used when creating new [PdfPagePathObject]
    /// instances. The fill mode can be changed on an object-by-object basis by calling the
    /// [PdfPagePathObject::set_fill_and_stroke_mode()] function.
    #[inline]
    fn default() -> Self {
        PdfPathFillMode::Winding
    }
}

/// A single `PdfPageObject` of type `PdfPageObjectType::Path`. The page object defines a path.
///
/// Paths define shapes, trajectories, and regions of all sorts. They are used to draw
/// lines, define the shapes of filled areas, and specify boundaries for clipping other
/// graphics. A path is composed of one or more _path segments_, each specifying
/// a straight or curved line segment. Each segment may connect to one another, forming a
/// _closed sub-path_, or may be disconnected from one another, forming one or more
/// _open sub-paths_. A path therefore is made up of one or more disconnected sub-paths, each
/// comprising a sequence of connected segments. Closed sub-paths can be filled;
/// both closed and open sub-paths can be stroked. The topology of the path is unrestricted;
/// it may be concave or convex, may contain multiple sub-paths representing disjoint areas,
/// and may intersect itself in arbitrary ways.
///
/// Page objects can be created either attached to a `PdfPage` (in which case the page object's
/// memory is owned by the containing page) or detached from any page (in which case the page
/// object's memory is owned by the object). Page objects are not rendered until they are
/// attached to a page; page objects that are never attached to a page will be lost when they
/// fall out of scope.
///
/// The simplest way to create a path object that is immediately attached to a page is to call
/// one of the `PdfPageObjects::create_path_object_*()` functions to create lines, cubic Bézier curves,
/// rectangles, circles, and ellipses. Alternatively you can create a detached path object using
/// one of the following functions, but you must add the object to a containing `PdfPageObjects`
/// collection manually.
///
/// * [PdfPagePathObject::new()]: creates an empty detached path object. Segments can be added to the
/// path by sequentially calling one or more of the [PdfPagePathObject::move_to()],
/// [PdfPagePathObject::line_to()], or [PdfPagePathObject::bezier_to()] functions.
/// A closed sub-path can be created by calling the [PdfPagePathObject::close_path()]
/// function. Convenience functions for adding rectangles, circles, and ellipses are also
/// available with the [PdfPagePathObject::rect_to()], [PdfPagePathObject::circle_to()],
/// and [PdfPagePathObject::ellipse_to()] functions, which create the desired shapes by
/// constructing closed sub-paths from other path segments.
/// * [PdfPagePathObject::new_line()]: creates a detached path object initialized with a single straight line.
/// * [PdfPagePathObject::new_bezier()]: creates a detached path object initialized with a single cubic Bézier curve.
/// * [PdfPagePathObject::new_rect()]: creates a detached path object initialized with a rectangular path.
/// * [PdfPagePathObject::new_circle()]: creates a detached path object initialized with a circular path,
/// filling the given rectangle.
/// * [PdfPagePathObject::new_circle_at()]: creates a detached path object initialized with a circular path,
/// centered at a particular origin point with a given radius.
/// * [PdfPagePathObject::new_ellipse()]: creates a detached path object initialized with an elliptical path,
/// filling the given rectangle.
/// * [PdfPagePathObject::new_ellipse_at()]: creates a detached path object initialized with an elliptical path,
/// centered at a particular origin point with given horizontal and vertical radii.
///
/// The detached path object can later be attached to a page by calling the
/// `PdfPageObjects::add_path_object()` function.
pub struct PdfPagePathObject<'a> {
    object_handle: FPDF_PAGEOBJECT,
    page_handle: Option<FPDF_PAGE>,
    annotation_handle: Option<FPDF_ANNOTATION>,
    bindings: &'a dyn PdfiumLibraryBindings,
    current_point_x: PdfPoints,
    current_point_y: PdfPoints,
}

impl<'a> PdfPagePathObject<'a> {
    #[inline]
    pub(crate) fn from_pdfium(
        object_handle: FPDF_PAGEOBJECT,
        page_handle: Option<FPDF_PAGE>,
        annotation_handle: Option<FPDF_ANNOTATION>,
        bindings: &'a dyn PdfiumLibraryBindings,
    ) -> Self {
        PdfPagePathObject {
            object_handle,
            page_handle,
            annotation_handle,
            bindings,
            current_point_x: PdfPoints::ZERO,
            current_point_y: PdfPoints::ZERO,
        }
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with the given initial position and with the given fill and stroke
    /// settings applied. Both the stroke color and the stroke width must be provided for the
    /// path to be stroked.
    ///
    /// Other than setting the initial position, this path will be empty. Add additional segments
    /// to this path by calling one or more of the [PdfPagePathObject::move_to()],
    /// [PdfPagePathObject::line_to()], or [PdfPagePathObject::bezier_to()]
    /// functions. A closed sub-path can be created by calling the [PdfPagePathObject::close_path()]
    /// function. Convenience functions for adding rectangles, circles, and ellipses are also
    /// available with the [PdfPagePathObject::rect_to()], [PdfPagePathObject::circle_to()],
    /// and [PdfPagePathObject::ellipse_to()] functions, which create the desired shapes by
    /// constructing closed sub-paths from other path segments.
    #[inline]
    pub fn new(
        document: &PdfDocument<'a>,
        x: PdfPoints,
        y: PdfPoints,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_from_bindings(
            document.bindings(),
            x,
            y,
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    pub(crate) fn new_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        x: PdfPoints,
        y: PdfPoints,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        let handle = bindings.FPDFPageObj_CreateNewPath(x.value, y.value);

        if handle.is_null() {
            if let Some(error) = bindings.get_pdfium_last_error() {
                Err(PdfiumError::PdfiumLibraryInternalError(error))
            } else {
                // This would be an unusual situation; a null handle indicating failure,
                // yet Pdfium's error code indicates success.

                Err(PdfiumError::PdfiumLibraryInternalError(
                    PdfiumInternalError::Unknown,
                ))
            }
        } else {
            let mut result = PdfPagePathObject {
                object_handle: handle,
                page_handle: None,
                annotation_handle: None,
                bindings,
                current_point_x: x,
                current_point_y: y,
            };

            result.move_to(x, y)?;

            let do_stroke = if let Some(stroke_color) = stroke_color {
                if let Some(stroke_width) = stroke_width {
                    result.set_stroke_color(stroke_color)?;
                    result.set_stroke_width(stroke_width)?;

                    true
                } else {
                    false
                }
            } else {
                false
            };

            let fill_mode = if let Some(fill_color) = fill_color {
                result.set_fill_color(fill_color)?;

                PdfPathFillMode::default()
            } else {
                PdfPathFillMode::None
            };

            result.set_fill_and_stroke_mode(fill_mode, do_stroke)?;

            Ok(result)
        }
    }

    #[inline]
    pub(crate) fn new_line_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        x1: PdfPoints,
        y1: PdfPoints,
        x2: PdfPoints,
        y2: PdfPoints,
        stroke_color: PdfColor,
        stroke_width: PdfPoints,
    ) -> Result<Self, PdfiumError> {
        let mut result = Self::new_from_bindings(
            bindings,
            x1,
            y1,
            Some(stroke_color),
            Some(stroke_width),
            None,
        )?;

        result.line_to(x2, y2)?;

        Ok(result)
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with a line with the given start and end coordinates,
    /// and with the given stroke settings applied.
    #[inline]
    pub fn new_line(
        document: &PdfDocument<'a>,
        x1: PdfPoints,
        y1: PdfPoints,
        x2: PdfPoints,
        y2: PdfPoints,
        stroke_color: PdfColor,
        stroke_width: PdfPoints,
    ) -> Result<Self, PdfiumError> {
        Self::new_line_from_bindings(
            document.bindings(),
            x1,
            y1,
            x2,
            y2,
            stroke_color,
            stroke_width,
        )
    }

    #[allow(clippy::too_many_arguments)]
    #[inline]
    pub(crate) fn new_bezier_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        x1: PdfPoints,
        y1: PdfPoints,
        x2: PdfPoints,
        y2: PdfPoints,
        control1_x: PdfPoints,
        control1_y: PdfPoints,
        control2_x: PdfPoints,
        control2_y: PdfPoints,
        stroke_color: PdfColor,
        stroke_width: PdfPoints,
    ) -> Result<Self, PdfiumError> {
        let mut result = Self::new_from_bindings(
            bindings,
            x1,
            y1,
            Some(stroke_color),
            Some(stroke_width),
            None,
        )?;

        result.bezier_to(x2, y2, control1_x, control1_y, control2_x, control2_y)?;

        Ok(result)
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with a cubic Bézier curve with the given start, end,
    /// and control point coordinates, and with the given stroke settings applied.
    #[allow(clippy::too_many_arguments)]
    #[inline]
    pub fn new_bezier(
        document: &PdfDocument<'a>,
        x1: PdfPoints,
        y1: PdfPoints,
        x2: PdfPoints,
        y2: PdfPoints,
        control1_x: PdfPoints,
        control1_y: PdfPoints,
        control2_x: PdfPoints,
        control2_y: PdfPoints,
        stroke_color: PdfColor,
        stroke_width: PdfPoints,
    ) -> Result<Self, PdfiumError> {
        Self::new_bezier_from_bindings(
            document.bindings(),
            x1,
            y1,
            x2,
            y2,
            control1_x,
            control1_y,
            control2_x,
            control2_y,
            stroke_color,
            stroke_width,
        )
    }

    #[inline]
    pub(crate) fn new_rect_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        rect: PdfRect,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        let mut result = Self::new_from_bindings(
            bindings,
            rect.left,
            rect.bottom,
            stroke_color,
            stroke_width,
            fill_color,
        )?;

        result.rect_to(rect.right, rect.top)?;

        Ok(result)
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with a path for the given rectangle, with the given
    /// fill and stroke settings applied. Both the stroke color and the stroke width must be
    /// provided for the rectangle to be stroked.
    #[inline]
    pub fn new_rect(
        document: &PdfDocument<'a>,
        rect: PdfRect,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_rect_from_bindings(
            document.bindings(),
            rect,
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    #[inline]
    pub(crate) fn new_circle_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        rect: PdfRect,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        let mut result = Self::new_from_bindings(
            bindings,
            rect.left,
            rect.bottom,
            stroke_color,
            stroke_width,
            fill_color,
        )?;

        result.circle_to(rect.right, rect.top)?;

        Ok(result)
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with a circle that fills the given rectangle, with the given
    /// fill and stroke settings applied. Both the stroke color and the stroke width must be
    /// provided for the circle to be stroked.
    #[inline]
    pub fn new_circle(
        document: &PdfDocument<'a>,
        rect: PdfRect,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_circle_from_bindings(
            document.bindings(),
            rect,
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    #[inline]
    pub(crate) fn new_circle_at_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        center_x: PdfPoints,
        center_y: PdfPoints,
        radius: PdfPoints,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_circle_from_bindings(
            bindings,
            PdfRect::new(
                center_y - radius,
                center_x - radius,
                center_y + radius,
                center_x + radius,
            ),
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with a circle centered at the given coordinates, with the
    /// given radius, and with the given fill and stroke settings applied. Both the stroke color
    /// and the stroke width must be provided for the circle to be stroked.
    #[inline]
    pub fn new_circle_at(
        document: &PdfDocument<'a>,
        center_x: PdfPoints,
        center_y: PdfPoints,
        radius: PdfPoints,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_circle_at_from_bindings(
            document.bindings(),
            center_x,
            center_y,
            radius,
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    #[inline]
    pub(crate) fn new_ellipse_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        rect: PdfRect,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        let mut result = Self::new_from_bindings(
            bindings,
            rect.left,
            rect.bottom,
            stroke_color,
            stroke_width,
            fill_color,
        )?;

        result.ellipse_to(rect.right, rect.top)?;

        Ok(result)
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with an ellipse that fills the given rectangle, with the given
    /// fill and stroke settings applied. Both the stroke color and the stroke width must be
    /// provided for the ellipse to be stroked.
    #[inline]
    pub fn new_ellipse(
        document: &PdfDocument<'a>,
        rect: PdfRect,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_ellipse_from_bindings(
            document.bindings(),
            rect,
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    #[allow(clippy::too_many_arguments)]
    #[inline]
    pub(crate) fn new_ellipse_at_from_bindings(
        bindings: &'a dyn PdfiumLibraryBindings,
        center_x: PdfPoints,
        center_y: PdfPoints,
        x_radius: PdfPoints,
        y_radius: PdfPoints,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_ellipse_from_bindings(
            bindings,
            PdfRect::new(
                center_y - y_radius,
                center_x - x_radius,
                center_y + y_radius,
                center_x + x_radius,
            ),
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    /// Creates a new [PdfPagePathObject] from the given arguments. The returned page object
    /// will not be rendered until it is added to a `PdfPage` using the
    /// `PdfPageObjects::add_path_object()` function.
    ///
    /// The new path will be created with an ellipse centered at the given coordinates, with the
    /// given horizontal and vertical radii, and with the given fill and stroke settings applied.
    /// Both the stroke color and the stroke width must be provided for the ellipse to be stroked.
    #[allow(clippy::too_many_arguments)]
    #[inline]
    pub fn new_ellipse_at(
        document: &PdfDocument<'a>,
        center_x: PdfPoints,
        center_y: PdfPoints,
        x_radius: PdfPoints,
        y_radius: PdfPoints,
        stroke_color: Option<PdfColor>,
        stroke_width: Option<PdfPoints>,
        fill_color: Option<PdfColor>,
    ) -> Result<Self, PdfiumError> {
        Self::new_ellipse_at_from_bindings(
            document.bindings(),
            center_x,
            center_y,
            x_radius,
            y_radius,
            stroke_color,
            stroke_width,
            fill_color,
        )
    }

    /// Begins a new sub-path in this [PdfPagePathObject] by moving the current point to the
    /// given coordinates, omitting any connecting line segment.
    pub fn move_to(&mut self, x: PdfPoints, y: PdfPoints) -> Result<(), PdfiumError> {
        if self.bindings.is_true(self.bindings.FPDFPath_MoveTo(
            self.object_handle,
            x.value,
            y.value,
        )) {
            self.current_point_x = x;
            self.current_point_y = y;

            Ok(())
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Appends a straight line segment to this [PdfPagePathObject] from the current point to the
    /// given coordinates. The new current point is set to the given coordinates.
    pub fn line_to(&mut self, x: PdfPoints, y: PdfPoints) -> Result<(), PdfiumError> {
        if self.bindings.is_true(self.bindings.FPDFPath_LineTo(
            self.object_handle,
            x.value,
            y.value,
        )) {
            self.current_point_x = x;
            self.current_point_y = y;

            Ok(())
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Appends a cubic Bézier curve to this [PdfPagePathObject] from the current point to the
    /// given coordinates, using the two given Bézier control points. The new current point
    /// is set to the given coordinates.
    pub fn bezier_to(
        &mut self,
        x: PdfPoints,
        y: PdfPoints,
        control1_x: PdfPoints,
        control1_y: PdfPoints,
        control2_x: PdfPoints,
        control2_y: PdfPoints,
    ) -> Result<(), PdfiumError> {
        if self.bindings.is_true(self.bindings.FPDFPath_BezierTo(
            self.object_handle,
            control1_x.value,
            control1_y.value,
            control2_x.value,
            control2_y.value,
            x.value,
            y.value,
        )) {
            self.current_point_x = x;
            self.current_point_y = y;

            Ok(())
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Appends a rectangle to this [PdfPagePathObject] by drawing four line segments
    /// from the current point, ending at the given coordinates. The current sub-path will be closed.
    /// The new current point is set to the given coordinates.
    pub fn rect_to(&mut self, x: PdfPoints, y: PdfPoints) -> Result<(), PdfiumError> {
        let orig_x = self.current_point_x;

        let orig_y = self.current_point_y;

        self.close_path()?;
        self.line_to(orig_x, y)?;
        self.line_to(x, y)?;
        self.line_to(x, orig_y)?;
        self.close_path()?;
        self.move_to(x, y)
    }

    /// Appends an ellipse to this [PdfPagePathObject] by drawing four Bézier curves approximating
    /// an ellipse filling a rectangle from the current point to the given coordinates.
    /// The current sub-path will be closed. The new current point is set to the given coordinates.
    pub fn ellipse_to(&mut self, x: PdfPoints, y: PdfPoints) -> Result<(), PdfiumError> {
        let x_radius = (x - self.current_point_x) / 2.0;

        let y_radius = (y - self.current_point_y) / 2.0;

        self.close_path()?;
        self.move_to(
            self.current_point_x + x_radius,
            self.current_point_y + y_radius,
        )?;
        self.ellipse(x_radius, y_radius)?;
        self.move_to(x, y)
    }

    /// Appends a circle to this [PdfPagePathObject] by drawing four Bézier curves approximating
    /// a circle filling a rectangle from the current point to the given coordinates.
    /// The current sub-path will be closed. The new current point is set to the given coordinates.
    ///
    /// Note that perfect circles cannot be represented exactly using Bézier curves. However,
    /// a very close approximation, more than sufficient to please the human eye, can be achieved
    /// using four Bézier curves, one for each quadrant of the circle.
    pub fn circle_to(&mut self, x: PdfPoints, y: PdfPoints) -> Result<(), PdfiumError> {
        let radius = (x - self.current_point_x) / 2.0;

        self.move_to(self.current_point_x + radius, self.current_point_y + radius)?;
        self.ellipse(radius, radius)?;
        self.move_to(x, y)
    }

    /// Draws an ellipse at the current point using the given horizontal and vertical radii.
    /// The ellipse will be constructed using four Bézier curves, one for each quadrant.
    fn ellipse(&mut self, x_radius: PdfPoints, y_radius: PdfPoints) -> Result<(), PdfiumError> {
        // Ellipse approximation method: https://spencermortensen.com/articles/bezier-circle/
        // Implementation based on: https://stackoverflow.com/a/2007782

        const C: f32 = 0.551915;

        let x_c = x_radius * C;

        let y_c = y_radius * C;

        let orig_x = self.current_point_x;

        let orig_y = self.current_point_y;

        self.move_to(orig_x - x_radius, orig_y)?;
        self.bezier_to(
            orig_x,
            orig_y + y_radius,
            orig_x - x_radius,
            orig_y + y_c,
            orig_x - x_c,
            orig_y + y_radius,
        )?;
        self.bezier_to(
            orig_x + x_radius,
            orig_y,
            orig_x + x_c,
            orig_y + y_radius,
            orig_x + x_radius,
            orig_y + y_c,
        )?;
        self.bezier_to(
            orig_x,
            orig_y - y_radius,
            orig_x + x_radius,
            orig_y - y_c,
            orig_x + x_c,
            orig_y - y_radius,
        )?;
        self.bezier_to(
            orig_x - x_radius,
            orig_y,
            orig_x - x_c,
            orig_y - y_radius,
            orig_x - x_radius,
            orig_y - y_c,
        )?;
        self.close_path()
    }

    /// Closes the current sub-path in this [PdfPagePathObject] by appending a straight line segment
    /// from the current point to the starting point of the sub-path.
    pub fn close_path(&mut self) -> Result<(), PdfiumError> {
        if self
            .bindings
            .is_true(self.bindings.FPDFPath_Close(self.object_handle))
        {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Returns the method used to determine which sub-paths of any path in this [PdfPagePathObject]
    /// should be filled.
    pub fn fill_mode(&self) -> Result<PdfPathFillMode, PdfiumError> {
        let mut raw_fill_mode: c_int = 0;

        let mut _raw_stroke: FPDF_BOOL = self.bindings().FALSE();

        if self
            .bindings()
            .is_true(self.bindings().FPDFPath_GetDrawMode(
                *self.get_object_handle(),
                &mut raw_fill_mode,
                &mut _raw_stroke,
            ))
        {
            PdfPathFillMode::from_pdfium(raw_fill_mode)
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings()
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Returns `true` if this [PdfPagePathObject] will be stroked, regardless of the path's
    /// stroke settings.
    ///
    /// Even if this path is set to be stroked, the stroke must be configured with a visible color
    /// and a non-zero width in order to actually be visible.
    pub fn is_stroked(&self) -> Result<bool, PdfiumError> {
        let mut _raw_fill_mode: c_int = 0;

        let mut raw_stroke: FPDF_BOOL = self.bindings().FALSE();

        if self
            .bindings()
            .is_true(self.bindings().FPDFPath_GetDrawMode(
                *self.get_object_handle(),
                &mut _raw_fill_mode,
                &mut raw_stroke,
            ))
        {
            Ok(self.bindings().is_true(raw_stroke))
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings()
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Sets the method used to determine which sub-paths of any path in this [PdfPagePathObject]
    /// should be filled, and whether or not any path in this [PdfPagePathObject] should be stroked.
    ///
    /// Even if this object's path is set to be stroked, the stroke must be configured with
    /// a visible color and a non-zero width in order to actually be visible.
    pub fn set_fill_and_stroke_mode(
        &mut self,
        fill_mode: PdfPathFillMode,
        do_stroke: bool,
    ) -> Result<(), PdfiumError> {
        if self
            .bindings()
            .is_true(self.bindings().FPDFPath_SetDrawMode(
                *self.get_object_handle(),
                fill_mode.as_pdfium() as c_int,
                self.bindings().bool_to_pdfium(do_stroke),
            ))
        {
            Ok(())
        } else {
            Err(PdfiumError::PdfiumLibraryInternalError(
                self.bindings()
                    .get_pdfium_last_error()
                    .unwrap_or(PdfiumInternalError::Unknown),
            ))
        }
    }

    /// Returns the collection of path segments currently defined by this [PdfPagePathObject].
    #[inline]
    pub fn segments(&self) -> PdfPagePathObjectSegments {
        PdfPagePathObjectSegments::from_pdfium(self.object_handle, self.bindings())
    }
}

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

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

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

    #[inline]
    fn clear_page_handle(&mut self) {
        self.page_handle = None;
    }

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

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

    #[inline]
    fn clear_annotation_handle(&mut self) {
        self.annotation_handle = None;
    }

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

    #[inline]
    fn is_cloneable_impl(&self) -> bool {
        // The path object can only be cloned if it contains no Bézier path segments.
        // Pdfium does not currently provide any way to retrieve the Bézier control points
        // of an existing Bézier path segment.

        !self
            .segments()
            .iter()
            .any(|segment| segment.segment_type() == PdfPathSegmentType::BezierTo)
    }

    fn try_clone_impl<'b>(
        &self,
        document: &PdfDocument<'b>,
    ) -> Result<PdfPageObject<'b>, PdfiumError> {
        let mut clone =
            PdfPagePathObject::new(document, PdfPoints::ZERO, PdfPoints::ZERO, None, None, None)?;

        clone.set_fill_and_stroke_mode(self.fill_mode()?, self.is_stroked()?)?;
        clone.set_fill_color(self.fill_color()?)?;
        clone.set_stroke_color(self.stroke_color()?)?;
        clone.set_stroke_width(self.stroke_width()?)?;
        clone.set_line_join(self.line_join()?)?;
        clone.set_line_cap(self.line_cap()?)?;

        for segment in self.segments().iter() {
            if segment.segment_type() == PdfPathSegmentType::Unknown {
                return Err(PdfiumError::PathObjectUnknownSegmentTypeNotCloneable);
            } else if segment.segment_type() == PdfPathSegmentType::BezierTo {
                return Err(PdfiumError::PathObjectBezierControlPointsNotCloneable);
            } else {
                match segment.segment_type() {
                    PdfPathSegmentType::Unknown | PdfPathSegmentType::BezierTo => {}
                    PdfPathSegmentType::LineTo => clone.line_to(segment.x(), segment.y())?,
                    PdfPathSegmentType::MoveTo => clone.move_to(segment.x(), segment.y())?,
                }

                if segment.is_close() {
                    clone.close_path()?;
                }
            }
        }

        clone.set_matrix(self.matrix()?)?;

        Ok(PdfPageObject::Path(clone))
    }
}

/// The collection of [PdfPathSegment] objects inside a path page object.
pub struct PdfPagePathObjectSegments<'a> {
    handle: FPDF_PAGEOBJECT,
    bindings: &'a dyn PdfiumLibraryBindings,
}

impl<'a> PdfPagePathObjectSegments<'a> {
    #[inline]
    pub(crate) fn from_pdfium(
        handle: FPDF_PAGEOBJECT,
        bindings: &'a dyn PdfiumLibraryBindings,
    ) -> Self {
        Self { handle, bindings }
    }
}

impl<'a> PdfPathSegments<'a> for PdfPagePathObjectSegments<'a> {
    #[inline]
    fn bindings(&self) -> &'a dyn PdfiumLibraryBindings {
        self.bindings
    }

    #[inline]
    fn len(&self) -> PdfPathSegmentIndex {
        self.bindings()
            .FPDFPath_CountSegments(self.handle)
            .try_into()
            .unwrap_or(0)
    }

    fn get(&self, index: PdfPathSegmentIndex) -> Result<PdfPathSegment<'a>, PdfiumError> {
        let handle = self
            .bindings()
            .FPDFPath_GetPathSegment(self.handle, index as c_int);

        if handle.is_null() {
            if let Some(error) = self.bindings().get_pdfium_last_error() {
                Err(PdfiumError::PdfiumLibraryInternalError(error))
            } else {
                // This would be an unusual situation; a null handle indicating failure,
                // yet Pdfium's error code indicates success.

                Err(PdfiumError::PdfiumLibraryInternalError(
                    PdfiumInternalError::Unknown,
                ))
            }
        } else {
            Ok(PdfPathSegment::from_pdfium(handle, self.bindings()))
        }
    }

    #[inline]
    fn iter(&'a self) -> PdfPathSegmentsIterator<'a> {
        PdfPathSegmentsIterator::new(self)
    }
}