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
//! Defines the [PdfBitmapConfig] struct, a builder-based approach to configuring
//! the rendering of `PdfBitmap` objects from one or more `PdfPage` objects.

use crate::bindgen::{
    FPDF_ANNOT, FPDF_CONVERT_FILL_TO_STROKE, FPDF_DWORD, FPDF_GRAYSCALE, FPDF_LCD_TEXT,
    FPDF_NO_NATIVETEXT, FPDF_PRINTING, FPDF_RENDER_FORCEHALFTONE, FPDF_RENDER_LIMITEDIMAGECACHE,
    FPDF_RENDER_NO_SMOOTHIMAGE, FPDF_RENDER_NO_SMOOTHPATH, FPDF_RENDER_NO_SMOOTHTEXT,
    FPDF_REVERSE_BYTE_ORDER,
};
use crate::bitmap::{PdfBitmapFormat, PdfBitmapRotation};
use crate::color::PdfColor;
use crate::form::PdfFormFieldType;
use crate::page::PdfPageOrientation::{Landscape, Portrait};
use crate::page::{PdfPage, PdfPageOrientation};

/// Configures the scaling, rotation, and rendering settings that should be applied to
/// a PdfPage to create a `PdfBitmap` for that page. [PdfBitmapConfig] can accommodate pages of
/// different sizes while correctly maintaining each page's aspect ratio, automatically
/// rotate portrait or landscape pages, generate page thumbnails, and apply maximum and
/// minimum pixel sizes to the scaled width and height of the final bitmap.
pub struct PdfBitmapConfig {
    target_width: Option<u16>,
    target_height: Option<u16>,
    scale_width_factor: Option<f32>,
    scale_height_factor: Option<f32>,
    maximum_width: Option<u16>,
    maximum_height: Option<u16>,
    portrait_rotation: PdfBitmapRotation,
    portrait_rotation_do_rotate_constraints: bool,
    landscape_rotation: PdfBitmapRotation,
    landscape_rotation_do_rotate_constraints: bool,
    format: PdfBitmapFormat,
    do_render_form_data: bool,
    form_field_highlight: Vec<(PdfFormFieldType, PdfColor)>,

    // The fields below set Pdfium's page rendering flags. Coverage for the
    // FPDF_DEBUG_INFO and FPDF_NO_CATCH flags is omitted since they are obsolete.
    do_set_flag_render_annotations: bool,     // Sets FPDF_ANNOT
    do_set_flag_use_lcd_text_rendering: bool, // Sets FPDF_LCD_TEXT
    do_set_flag_no_native_text: bool,         // Sets FPDF_NO_NATIVETEXT
    do_set_flag_grayscale: bool,              // Sets FPDF_GRAYSCALE
    do_set_flag_render_limited_image_cache: bool, // Sets FPDF_RENDER_LIMITEDIMAGECACHE
    do_set_flag_render_force_half_tone: bool, // Sets FPDF_RENDER_FORCEHALFTONE
    do_set_flag_render_for_printing: bool,    // Sets FPDF_PRINTING
    do_set_flag_render_no_smooth_text: bool,  // Sets FPDF_RENDER_NO_SMOOTHTEXT
    do_set_flag_render_no_smooth_image: bool, // Sets FPDF_RENDER_NO_SMOOTHIMAGE
    do_set_flag_render_no_smooth_path: bool,  // Sets FPDF_RENDER_NO_SMOOTHPATH
    do_set_flag_reverse_byte_order: bool,     // Sets FPDF_REVERSE_BYTE_ORDER
    do_set_flag_convert_fill_to_stroke: bool, // Sets FPDF_CONVERT_FILL_TO_STROKE
}

impl PdfBitmapConfig {
    /// Creates a new [PdfBitmapConfig] object with all settings initialized with their default values.
    pub fn new() -> Self {
        PdfBitmapConfig {
            target_width: None,
            target_height: None,
            scale_width_factor: None,
            scale_height_factor: None,
            maximum_width: None,
            maximum_height: None,
            portrait_rotation: PdfBitmapRotation::None,
            portrait_rotation_do_rotate_constraints: false,
            landscape_rotation: PdfBitmapRotation::None,
            landscape_rotation_do_rotate_constraints: false,
            format: PdfBitmapFormat::BGRA,
            do_render_form_data: true,
            form_field_highlight: vec![],
            do_set_flag_render_annotations: true,
            do_set_flag_use_lcd_text_rendering: false,
            do_set_flag_no_native_text: false,
            do_set_flag_grayscale: false,
            do_set_flag_render_limited_image_cache: false,
            do_set_flag_render_force_half_tone: false,
            do_set_flag_render_for_printing: false,
            do_set_flag_render_no_smooth_text: false,
            do_set_flag_render_no_smooth_image: false,
            do_set_flag_render_no_smooth_path: false,
            do_set_flag_reverse_byte_order: false,
            do_set_flag_convert_fill_to_stroke: false,
        }
    }

    /// Applies settings suitable for generating a thumbnail.
    ///
    /// * The source [PdfPage] will be rendered with a maximum width and height of the given
    /// pixel size
    /// * The page will not be rotated, irrespective of its orientation
    /// * Image quality settings will be reduced to improve performance
    /// * Annotations and user-filled form field data will not be rendered.
    ///
    /// These settings are applied to this [PdfBitmapConfig] object immediately and can be
    /// selectively overridden by later function calls. For instance, a later call to
    /// [PdfBitmapConfig::rotate()] can specify a custom rotation setting that will apply
    /// to the thumbnail.
    #[inline]
    pub fn thumbnail(self, size: u8) -> Self {
        self.set_target_size(size as u16, size as u16)
            .set_maximum_width(size as u16)
            .set_maximum_height(size as u16)
            .rotate(PdfBitmapRotation::None, false)
            .use_print_quality(false)
            .set_image_smoothing(false)
            .render_annotations(false)
            .render_form_data(false)
    }

    /// Converts the width and height of a [PdfPage] from points to pixels, scaling each
    /// dimension to the given target pixel sizes. The aspect ratio of the source page
    /// will not be maintained.
    #[inline]
    pub fn set_target_size(self, width: u16, height: u16) -> Self {
        self.set_target_width(width).set_target_height(height)
    }

    /// Converts the width of a [PdfPage] from points to pixels, scaling the source page
    /// width to the given target pixel width. The aspect ratio of the source page
    /// will be maintained so long as there is no call to [PdfBitmapConfig::set_target_size()]
    /// or [PdfBitmapConfig::set_target_height()] that overrides it.
    #[inline]
    pub fn set_target_width(mut self, width: u16) -> Self {
        self.target_width = Some(width);

        self
    }

    /// Converts the height of a [PdfPage] from points to pixels, scaling the source page
    /// height to the given target pixel height. The aspect ratio of the source page
    /// will be maintained so long as there is no call to [PdfBitmapConfig::set_target_size()]
    /// or [PdfBitmapConfig::set_target_width()] that overrides it.
    #[inline]
    pub fn set_target_height(mut self, height: u16) -> Self {
        self.target_height = Some(height);

        self
    }

    /// Applies settings to this [PdfBitmapConfig] suitable for filling the given
    /// screen display size.
    ///
    /// The source page's dimensions will be scaled so that both width and height attempt
    /// to fill, but do not exceed, the given pixel dimensions. The aspect ratio of the
    /// source page will be maintained. Landscape pages will be automatically rotated
    /// by 90 degrees and will be scaled down if necessary to fit the display width.
    #[inline]
    pub fn scale_page_to_display_size(mut self, width: u16, height: u16) -> Self {
        self.scale_width_factor = None;
        self.scale_height_factor = None;

        self.set_target_width(width)
            .set_maximum_width(width)
            .set_maximum_height(height)
            .rotate_if_landscape(PdfBitmapRotation::Degrees90, true)
    }

    /// Converts the width and height of a [PdfPage] from points to pixels by applying
    /// the given scale factor to both dimensions. The aspect ratio of the source page
    /// will be maintained. Overrides any previous call to [PdfBitmapConfig::scale_page_by_factor()],
    /// [PdfBitmapConfig::scale_page_width_by_factor()], or [PdfBitmapConfig::scale_page_height_by_factor()].
    #[inline]
    pub fn scale_page_by_factor(self, scale: f32) -> Self {
        let result = self.scale_page_width_by_factor(scale);

        result.scale_page_height_by_factor(scale)
    }

    /// Converts the width of the [PdfPage] from points to pixels by applying the given
    /// scale factor. The aspect ratio of the source page will not be maintained if a
    /// different scale factor is applied to the height. Overrides any previous call to
    /// [PdfBitmapConfig::scale_page_by_factor()], [PdfBitmapConfig::scale_page_width_by_factor()],
    /// or [PdfBitmapConfig::scale_page_height_by_factor()].
    #[inline]
    pub fn scale_page_width_by_factor(mut self, scale: f32) -> Self {
        self.scale_width_factor = Some(scale);

        self
    }

    /// Converts the height of the [PdfPage] from points to pixels by applying the given
    /// scale factor. The aspect ratio of the source page will not be maintained if a
    /// different scale factor is applied to the width. Overrides any previous call to
    /// [PdfBitmapConfig::scale_page_by_factor()], [PdfBitmapConfig::scale_page_width_by_factor()],
    /// or [PdfBitmapConfig::scale_page_height_by_factor()].
    #[inline]
    pub fn scale_page_height_by_factor(mut self, scale: f32) -> Self {
        self.scale_height_factor = Some(scale);

        self
    }

    /// Specifies that the final pixel width of the [PdfPage] will not exceed the given maximum.
    #[inline]
    pub fn set_maximum_width(mut self, width: u16) -> Self {
        self.maximum_width = Some(width);

        self
    }

    /// Specifies that the final pixel height of the [PdfPage] will not exceed the given maximum.
    #[inline]
    pub fn set_maximum_height(mut self, height: u16) -> Self {
        self.maximum_height = Some(height);

        self
    }

    /// Applies the given rotation setting to the [PdfPage] during rendering, irrespective
    /// of its orientation. If the given flag is set to `true` then any maximum
    /// constraint on the final pixel width set by a call to [PdfBitmapConfig::set_maximum_width()]
    /// will be rotated so it becomes a constraint on the final pixel height, and any
    /// maximum constraint on the final pixel height set by a call to [PdfBitmapConfig::set_maximum_height()]
    /// will be rotated so it becomes a constraint on the final pixel width.
    #[inline]
    pub fn rotate(self, rotation: PdfBitmapRotation, do_rotate_constraints: bool) -> Self {
        self.rotate_if_portait(rotation, do_rotate_constraints)
            .rotate_if_landscape(rotation, do_rotate_constraints)
    }

    /// Applies the given rotation settings to the [PdfPage] during rendering, if the page
    /// is in portrait orientation. If the given flag is set to `true` and the given
    /// rotation setting is [PdfBitmapRotation::Degrees90] or [PdfBitmapRotation::Degrees270]
    /// then any maximum constraint on the final pixel width set by a call to [PdfBitmapConfig::set_maximum_width()]
    /// will be rotated so it becomes a constraint on the final pixel height and any
    /// maximum constraint on the final pixel height set by a call to [PdfBitmapConfig::set_maximum_height()]
    /// will be rotated so it becomes a constraint on the final pixel width.
    #[inline]
    pub fn rotate_if_portait(
        mut self,
        rotation: PdfBitmapRotation,
        do_rotate_constraints: bool,
    ) -> Self {
        self.portrait_rotation = rotation;

        if rotation == PdfBitmapRotation::Degrees90 || rotation == PdfBitmapRotation::Degrees270 {
            self.portrait_rotation_do_rotate_constraints = do_rotate_constraints;
        }

        self
    }

    /// Applies the given rotation settings to the [PdfPage] during rendering, if the page
    /// is in landscape orientation. If the given flag is set to `true` and the given
    /// rotation setting is [PdfBitmapRotation::Degrees90] or [PdfBitmapRotation::Degrees270]
    /// then any maximum constraint on the final pixel width set by a call to [PdfBitmapConfig::set_maximum_width()]
    /// will be rotated so it becomes a constraint on the final pixel height and any
    /// maximum constraint on the final pixel height set by a call to [PdfBitmapConfig::set_maximum_height()]
    /// will be rotated so it becomes a constraint on the final pixel width.
    #[inline]
    pub fn rotate_if_landscape(
        mut self,
        rotation: PdfBitmapRotation,
        do_rotate_constraints: bool,
    ) -> Self {
        self.landscape_rotation = rotation;

        if rotation == PdfBitmapRotation::Degrees90 || rotation == PdfBitmapRotation::Degrees270 {
            self.landscape_rotation_do_rotate_constraints = do_rotate_constraints;
        }

        self
    }

    /// Sets the pixel format that will be used during rendering of the [PdfPage].
    /// The default is [PdfBitmapFormat::BGRA].
    #[inline]
    pub fn set_format(mut self, format: PdfBitmapFormat) -> Self {
        self.format = format;

        self
    }

    /// Controls whether form data widgets and user-supplied form data should be included
    /// during rendering of the [PdfPage]. The default is `true`. The setting has no effect
    /// if the `PdfDocument` containing the `PdfPage` does not include an embedded `PdfForm`.
    #[inline]
    pub fn render_form_data(mut self, do_render: bool) -> Self {
        self.do_render_form_data = do_render;

        self
    }

    /// Controls whether user-supplied annotations should be included during rendering of
    /// the [PdfPage]. The default is `true`.
    #[inline]
    pub fn render_annotations(mut self, do_render: bool) -> Self {
        self.do_set_flag_render_annotations = do_render;

        self
    }

    /// Controls whether text rendering should be optimized for LCD display.
    /// The default is `false`.
    /// Has no effect if anti-aliasing of text has been disabled by a call to
    /// `PdfBitmapConfig::set_text_smoothing(false)`.
    #[inline]
    pub fn use_lcd_text_rendering(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_use_lcd_text_rendering = do_set_flag;

        self
    }

    /// Controls whether platform text rendering should be disabled on platforms that support it.
    /// The alternative is for Pdfium to render all text internally, which may give more
    /// consistent rendering results across platforms but may also be slower.
    /// The default is `false`.
    #[inline]
    pub fn disable_native_text_rendering(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_no_native_text = do_set_flag;

        self
    }

    /// Controls whether rendering output should be grayscale rather than full color.
    /// The default is `false`.
    #[inline]
    pub fn use_grayscale_rendering(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_grayscale = do_set_flag;

        self
    }

    /// Controls whether Pdfium should limit its image cache size during rendering.
    /// A smaller cache size may result in lower memory usage at the cost of slower rendering.
    /// The default is `false`.
    #[inline]
    pub fn limit_render_image_cache_size(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_render_limited_image_cache = do_set_flag;

        self
    }

    /// Controls whether Pdfium should always use halftone for image stretching.
    /// Halftone image stretching is often higher quality than linear image stretching
    /// but is much slower. The default is `false`.
    #[inline]
    pub fn force_half_tone(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_render_force_half_tone = do_set_flag;

        self
    }

    /// Controls whether Pdfium should render for printing. The default is `false`.
    ///
    /// Certain PDF files may stipulate different quality settings for on-screen display
    /// compared to printing. For these files, changing this setting to `true` will result
    /// in a higher quality rendered bitmap but slower performance. For PDF files that do
    /// not stipulate different quality settings, changing this setting will have no effect.
    #[inline]
    pub fn use_print_quality(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_render_for_printing = do_set_flag;

        self
    }

    /// Controls whether rendered text should be anti-aliased.
    /// The default is `true`.
    /// The enabling of LCD-optimized text rendering via a call to
    /// `PdfiumBitmapConfig::use_lcd_text_rendering(true)` has no effect if this flag
    /// is set to `false`.
    #[inline]
    pub fn set_text_smoothing(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_render_no_smooth_text = !do_set_flag;

        self
    }

    /// Controls whether rendered images should be anti-aliased.
    /// The default is `true`.
    #[inline]
    pub fn set_image_smoothing(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_render_no_smooth_image = !do_set_flag;

        self
    }

    /// Controls whether rendered vector paths should be anti-aliased.
    /// The default is `true`.
    #[inline]
    pub fn set_path_smoothing(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_render_no_smooth_path = !do_set_flag;

        self
    }

    /// Controls whether the byte order of generated image data should be reversed
    /// during rendering. The default is `false`. There should generally be no need
    /// to set this flag, unless you want to do raw image processing and specifically
    /// need the byte data returned by [crate::bitmap::PdfBitmap::as_bytes()] to be reversed.
    #[inline]
    pub fn set_reverse_byte_order(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_reverse_byte_order = do_set_flag;

        self
    }

    /// Controls whether rendered vector fill paths need to be stroked.
    /// The default is `false`.
    #[inline]
    pub fn render_fills_as_strokes(mut self, do_set_flag: bool) -> Self {
        self.do_set_flag_convert_fill_to_stroke = do_set_flag;

        self
    }

    /// Highlights all rendered form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_all_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::Unknown, color)
    }

    /// Highlights all rendered push button form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_button_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::PushButton, color)
    }

    /// Highlights all rendered checkbox form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_checkbox_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::Checkbox, color)
    }

    /// Highlights all rendered radio button form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_radio_button_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::RadioButton, color)
    }

    /// Highlights all rendered combobox form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_combobox_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::ComboBox, color)
    }

    /// Highlights all rendered listbox form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_listbox_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::ListBox, color)
    }

    /// Highlights all rendered text entry form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_text_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::TextField, color)
    }

    /// Highlights all rendered signature form fields with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_signature_form_fields(self, color: PdfColor) -> Self {
        self.highlight_form_fields_of_type(PdfFormFieldType::Signature, color)
    }

    /// Highlights all rendered form fields matching the given type with the given color.
    /// Note that specifying a solid color with no opacity will overprint any user data in the field.
    #[inline]
    pub fn highlight_form_fields_of_type(
        mut self,
        form_field_type: PdfFormFieldType,
        color: PdfColor,
    ) -> Self {
        self.form_field_highlight.push((form_field_type, color));

        self
    }

    /// Computes the pixel dimensions and rotation settings for the given [PdfPage]
    /// based on the configuration of this [PdfBitmapConfig].
    #[inline]
    pub(crate) fn apply_to_page(&self, page: &PdfPage) -> PdfBitmapRenderSettings {
        let source_width = page.width();

        let source_height = page.height();

        let source_orientation =
            PdfPageOrientation::from_width_and_height(source_width, source_height);

        // Do we need to apply any rotation?

        let (target_rotation, do_rotate_constraints) = if source_orientation == Portrait
            && self.portrait_rotation != PdfBitmapRotation::None
        {
            (
                self.portrait_rotation,
                self.portrait_rotation_do_rotate_constraints,
            )
        } else if source_orientation == Landscape
            && self.landscape_rotation != PdfBitmapRotation::None
        {
            (
                self.landscape_rotation,
                self.landscape_rotation_do_rotate_constraints,
            )
        } else {
            (PdfBitmapRotation::None, false)
        };

        let width_scale = if let Some(scale) = self.scale_width_factor {
            Some(scale)
        } else {
            self.target_width
                .map(|target| (target as f32) / source_width.value)
        };

        let height_scale = if let Some(scale) = self.scale_height_factor {
            Some(scale)
        } else {
            self.target_height
                .map(|target| (target as f32) / source_height.value)
        };

        // Maintain source aspect ratio if only one dimension's scale is set.

        let (do_maintain_aspect_ratio, mut width_scale, mut height_scale) =
            match (width_scale, height_scale) {
                (Some(width_scale), Some(height_scale)) => {
                    (width_scale == height_scale, width_scale, height_scale)
                }
                (Some(width_scale), None) => (true, width_scale, width_scale),
                (None, Some(height_scale)) => (true, height_scale, height_scale),
                (None, None) => {
                    // Set default scale to 1.0 if neither dimension is specified.

                    (false, 1.0, 1.0)
                }
            };

        // Apply constraints on maximum width and height, if any.

        let (source_width, source_height, width_constraint, height_constraint) =
            if do_rotate_constraints {
                (
                    source_height,
                    source_width,
                    self.maximum_height,
                    self.maximum_width,
                )
            } else {
                (
                    source_width,
                    source_height,
                    self.maximum_width,
                    self.maximum_height,
                )
            };

        if let Some(maximum) = width_constraint {
            let maximum = maximum as f32;

            if source_width.value * width_scale > maximum {
                // Constrain the width, so it does not exceed the maximum.

                width_scale = maximum / source_width.value;

                if do_maintain_aspect_ratio {
                    height_scale = width_scale;
                }
            }
        }

        if let Some(maximum) = height_constraint {
            let maximum = maximum as f32;

            if source_height.value * height_scale > maximum {
                // Constrain the height, so it does not exceed the maximum.

                height_scale = maximum / source_height.value;

                if do_maintain_aspect_ratio {
                    width_scale = height_scale;
                }
            }
        }

        // Compose render flags.

        let mut render_flags = 0;

        if self.do_set_flag_render_annotations {
            render_flags |= FPDF_ANNOT;
        }

        if self.do_set_flag_use_lcd_text_rendering {
            render_flags |= FPDF_LCD_TEXT;
        }

        if self.do_set_flag_no_native_text {
            render_flags |= FPDF_NO_NATIVETEXT;
        }

        if self.do_set_flag_grayscale {
            render_flags |= FPDF_GRAYSCALE;
        }

        if self.do_set_flag_render_limited_image_cache {
            render_flags |= FPDF_RENDER_LIMITEDIMAGECACHE;
        }

        if self.do_set_flag_render_force_half_tone {
            render_flags |= FPDF_RENDER_FORCEHALFTONE;
        }

        if self.do_set_flag_render_for_printing {
            render_flags |= FPDF_PRINTING;
        }

        if self.do_set_flag_render_no_smooth_text {
            render_flags |= FPDF_RENDER_NO_SMOOTHTEXT;
        }

        if self.do_set_flag_render_no_smooth_image {
            render_flags |= FPDF_RENDER_NO_SMOOTHIMAGE;
        }

        if self.do_set_flag_render_no_smooth_path {
            render_flags |= FPDF_RENDER_NO_SMOOTHPATH;
        }

        if self.do_set_flag_reverse_byte_order {
            render_flags |= FPDF_REVERSE_BYTE_ORDER;
        }

        if self.do_set_flag_convert_fill_to_stroke {
            render_flags |= FPDF_CONVERT_FILL_TO_STROKE;
        }

        PdfBitmapRenderSettings {
            width: (source_width.value * width_scale) as i32,
            height: (source_height.value * height_scale) as i32,
            format: self.format.as_pdfium() as i32,
            rotate: target_rotation.as_pdfium(),
            do_render_form_data: self.do_render_form_data,
            form_field_highlight: self
                .form_field_highlight
                .iter()
                .map(|(form_field_type, color)| {
                    (
                        form_field_type.as_pdfium() as i32,
                        color.as_pdfium_color_with_alpha(),
                    )
                })
                .collect::<Vec<_>>(),
            render_flags: render_flags as i32,
        }
    }
}

impl Default for PdfBitmapConfig {
    #[inline]
    fn default() -> Self {
        PdfBitmapConfig::new()
    }
}

#[derive(Debug, Clone)]
pub(crate) struct PdfBitmapRenderSettings {
    pub(crate) width: i32,
    pub(crate) height: i32,
    pub(crate) format: i32,
    pub(crate) rotate: i32,
    pub(crate) do_render_form_data: bool,
    pub(crate) form_field_highlight: Vec<(i32, (FPDF_DWORD, u8))>,
    pub(crate) render_flags: i32,
}