pdf_oxide 0.3.78

The fastest Rust PDF library — 0.8ms mean, 5× faster than the industry leaders, 100% pass rate on 3,830 real-world PDFs. Text extraction, Markdown/HTML conversion, PDF creation and editing.
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
//! Page rendering module for converting PDF pages to images.
//!
//! This module provides functionality to render PDF pages to raster images
//! using the pure-Rust `tiny-skia` library.
//!
//! ## Features
//!
//! - Render pages to PNG/JPEG images
//! - Configurable DPI and image quality
//! - Support for text, paths, and images
//! - Transparency and blend modes
//!
//! ## Example
//!
//! ```ignore
//! use pdf_oxide::api::Pdf;
//! use pdf_oxide::rendering::{RenderOptions, ImageFormat};
//!
//! let mut pdf = Pdf::open("document.pdf")?;
//! let image = pdf.render_page(0, &RenderOptions::default())?;
//! image.save("page1.png")?;
//! ```
//!
//! ## Architecture
//!
//! The rendering pipeline:
//!
//! 1. Parse page content stream into operators
//! 2. Execute operators against graphics state machine
//! 3. Rasterize paths, text, and images to tiny-skia pixmap
//! 4. Convert to output format (PNG/JPEG)

pub(crate) mod blend_nonsep;
pub(crate) mod ext_gstate;
pub(crate) mod mesh_shading;
pub(crate) mod page_renderer;
mod path_rasterizer;
pub(crate) mod resolution;
pub(crate) mod separation_renderer;
/// CMYK + spot-ink compositing sidecar used by the page renderer to
/// hold the §11.4 transparency-composite state during a page render.
///
/// Public so integration tests can drive the §11.7.4.2 dispatch
/// classifier ([`crate::rendering::sidecar::BlendModeClass`]) directly
/// without going through a rendered pixmap. Internal storage types
/// (`CmykSidecar`) remain `pub(crate)`.
pub mod sidecar;
mod text_rasterizer;

pub use page_renderer::{
    ImageFormat, PageRenderer, RenderOptions, RenderedImage, DEFAULT_MAX_OUTPUT_PIXELS,
};
pub use separation_renderer::{render_separation, render_separations, SeparationPlate};

use crate::content::GraphicsState;
use crate::error::Result;
use tiny_skia::{Color, Paint};

/// Create a Paint configured for fill operations from graphics state.
pub(crate) fn create_fill_paint(gs: &GraphicsState, blend_mode: &str) -> Paint<'static> {
    let (r, g, b) = gs.fill_color_rgb;
    let mut paint = Paint::default();

    // Note: render_mode == 3 (invisible text) is handled in the text rendering path,
    // not here, since this paint is also used for non-text fills (paths, shapes).
    paint.set_color(Color::from_rgba(r, g, b, gs.fill_alpha).unwrap_or(Color::BLACK));

    paint.anti_alias = true;

    if blend_mode != "Normal" {
        paint.blend_mode = pdf_blend_mode_to_skia(blend_mode);
    }

    paint
}

/// Create a Paint configured for stroke operations from graphics state.
pub(crate) fn create_stroke_paint(gs: &GraphicsState, blend_mode: &str) -> Paint<'static> {
    let (r, g, b) = gs.stroke_color_rgb;
    let mut paint = Paint::default();
    paint.set_color(Color::from_rgba(r, g, b, gs.stroke_alpha).unwrap_or(Color::BLACK));
    paint.anti_alias = true;

    if blend_mode != "Normal" {
        paint.blend_mode = pdf_blend_mode_to_skia(blend_mode);
    }

    paint
}

/// Convert PDF blend mode to tiny-skia.
pub(crate) fn pdf_blend_mode_to_skia(mode: &str) -> tiny_skia::BlendMode {
    match mode {
        "Normal" => tiny_skia::BlendMode::SourceOver,
        "Multiply" => tiny_skia::BlendMode::Multiply,
        "Screen" => tiny_skia::BlendMode::Screen,
        "Overlay" => tiny_skia::BlendMode::Overlay,
        "Darken" => tiny_skia::BlendMode::Darken,
        "Lighten" => tiny_skia::BlendMode::Lighten,
        "ColorDodge" => tiny_skia::BlendMode::ColorDodge,
        "ColorBurn" => tiny_skia::BlendMode::ColorBurn,
        "HardLight" => tiny_skia::BlendMode::HardLight,
        "SoftLight" => tiny_skia::BlendMode::SoftLight,
        "Difference" => tiny_skia::BlendMode::Difference,
        "Exclusion" => tiny_skia::BlendMode::Exclusion,
        _ => tiny_skia::BlendMode::SourceOver,
    }
}

/// Largest device-space coordinate a path may reach and still be handed to
/// tiny_skia. 2^24 is where f32 stops representing adjacent integers, but it
/// is not the operative bound: tiny_skia clips edges against the pixmap
/// (`edge_clipper.rs`, engaged whenever a path is not contained in the clip)
/// and keeps rasterizing well past that. The bound that matters is where the
/// rasterizer actually gives up — beyond it the antialiased run accounting
/// desynchronizes and panics (`alpha_runs.rs` `unwrap` on a run past the
/// accumulated buffer).
///
/// Measured against tiny_skia 0.12 at 72 dpi: fills and cubics alike still
/// rasterize correctly at 5e8 device units and produce nothing at 7e8, so
/// the bound is the last value confirmed to work. Only 5e8..7e8 is
/// unmeasured, and a draw landing in it is dropped although the rasterizer
/// would have coped. The decade below was measured too, because a real
/// document turned out to live there: a page in the corpus fills to 1.3e8
/// device units, which an earlier 1e8 bound discarded.
const MAX_DEVICE_COORD: f64 = 5.0e8;

/// The rectangle a page is rendered to: its `/CropBox` clipped to the
/// `/MediaBox`, or the media box when no crop box is given.
///
/// ISO 32000-1:2008 Table 30 on `/CropBox`: "A rectangle ... that shall define
/// the visible region of default user space. When the page is displayed or
/// printed, its contents **shall be clipped (cropped) to this rectangle** ...
/// Default value: the value of MediaBox."
///
/// The crop box was parsed onto `PageInfo` and then never consulted by either
/// renderer, so a cropped scan rendered at full media size showing the margins
/// the file asked to have cropped away. §14.11.2 also has the crop box taken as
/// its intersection with the media box, so a crop box larger than the medium
/// does not enlarge the page.
pub(crate) fn page_render_box(
    media_box: &crate::geometry::Rect,
    crop_box: Option<&crate::geometry::Rect>,
) -> crate::geometry::Rect {
    let Some(crop) = crop_box else {
        return *media_box;
    };
    let x0 = crop.x.max(media_box.x);
    let y0 = crop.y.max(media_box.y);
    let x1 = (crop.x + crop.width).min(media_box.x + media_box.width);
    let y1 = (crop.y + crop.height).min(media_box.y + media_box.height);
    // A crop box that does not overlap the medium describes nothing to show;
    // fall back to the media box rather than rendering an empty page.
    if x1 <= x0 || y1 <= y0 {
        return *media_box;
    }
    crate::geometry::Rect::from_points(x0, y0, x1, y1)
}

/// The page extent in points after the `/Rotate` turn, as `(width, height)`.
///
/// ISO 32000-1:2008 §7.7.3.3 Table 30: `/Rotate` is clockwise and a multiple
/// of 90, so a quarter turn swaps the axes.
pub(crate) fn rotated_page_extent(media_box: &crate::geometry::Rect, rotation: i32) -> (f32, f32) {
    if rotation.rem_euclid(360) == 90 || rotation.rem_euclid(360) == 270 {
        (media_box.height, media_box.width)
    } else {
        (media_box.width, media_box.height)
    }
}

/// The page's base transform: PDF user space to device pixels, including the
/// `/Rotate` turn and the y-up to y-down flip.
///
/// **Every case here has a negative determinant.** The flip from PDF's y-up
/// user space to the raster's y-down rows contributes one reflection, and a
/// quarter turn contributes none — so a matrix with a *positive* determinant
/// is a mirror image, not a rotation. That is a cheap invariant to check and
/// it is the one that failed: the composite renderer's 270° case was
/// corrected to `from_row(0, -s, -s, 0, …)` (determinant −s²) and the
/// separation renderer's copy was left as `from_row(0, s, -s, 0, …)`
/// (determinant +s²), so every ink plate of a `/Rotate 270` page came out
/// mirrored while the composite of the same page did not. Two renderers of
/// one page disagreed, which is why this lives in one place now.
///
/// `rotation` may be negative — `/Rotate -90` is legal and means 270 — so it
/// is normalised here rather than at each call site.
pub(crate) fn page_base_transform(
    media_box: &crate::geometry::Rect,
    rotation: i32,
    scale: f32,
) -> tiny_skia::Transform {
    use tiny_skia::Transform;
    let origin = Transform::from_translate(-media_box.x, -media_box.y);
    let (_, page_h) = rotated_page_extent(media_box, rotation);
    match rotation.rem_euclid(360) {
        // 90° CW: PDF (x, y) -> device (y·s, x·s).
        90 => origin.post_concat(Transform::from_row(0.0, scale, scale, 0.0, 0.0, 0.0)),
        180 => origin
            .post_scale(-scale, scale)
            .post_translate(media_box.width * scale, 0.0),
        // 270° CW: PDF (x, y) -> device ((H − y)·s, (W − x)·s).
        270 => origin.post_concat(Transform::from_row(
            0.0,
            -scale,
            -scale,
            0.0,
            media_box.height * scale,
            media_box.width * scale,
        )),
        _ => origin
            .post_scale(scale, -scale)
            .post_translate(0.0, page_h * scale),
    }
}

/// How far a stroke's outline may reach from its centerline, in device
/// units, before the width is narrowed. Measured separately from
/// [`MAX_DEVICE_COORD`] because it is a separate failure: a 10x10 rect
/// strokes correctly at width 1e9 (outline reach 5e9) and aborts the process
/// at 1e10 (5e10), even though the centerline is only ten units across. 5e8
/// keeps every width measured to rasterize, and its interior 5e8..5e10 is
/// likewise unmeasured.
const MAX_DEVICE_STROKE_REACH: f64 = 5.0e8;

/// Device-space bounds of `path` as `[min_x, min_y, max_x, max_y]`. `None`
/// when a corner is not finite — geometry we cannot place on the pixmap at
/// all.
fn device_bounds(path: &tiny_skia::Path, transform: tiny_skia::Transform) -> Option<[f64; 4]> {
    let (sx, kx, ky, sy, tx, ty) = (
        f64::from(transform.sx),
        f64::from(transform.kx),
        f64::from(transform.ky),
        f64::from(transform.sy),
        f64::from(transform.tx),
        f64::from(transform.ty),
    );
    let b = path.bounds();
    let (left, top) = (f64::from(b.left()), f64::from(b.top()));
    let (right, bottom) = (f64::from(b.right()), f64::from(b.bottom()));
    let mut out = [
        f64::INFINITY,
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::NEG_INFINITY,
    ];
    for (x, y) in [(left, top), (right, top), (left, bottom), (right, bottom)] {
        let dx = sx * x + kx * y + tx;
        let dy = ky * x + sy * y + ty;
        if !dx.is_finite() || !dy.is_finite() {
            return None;
        }
        out[0] = out[0].min(dx);
        out[1] = out[1].min(dy);
        out[2] = out[2].max(dx);
        out[3] = out[3].max(dy);
    }
    Some(out)
}

/// Whether a path's device-space bounds are representable enough to
/// rasterize. Used at the clip sites, which have no pixmap to cull against.
pub(crate) fn device_bounds_rasterizable(
    path: &tiny_skia::Path,
    transform: tiny_skia::Transform,
) -> bool {
    device_bounds(path, transform).is_some_and(|b| b.iter().all(|c| c.abs() <= MAX_DEVICE_COORD))
}

/// Whether a path's device bounds lie wholly outside a `width` x `height`
/// pixmap — i.e. the region it describes contains none of the page.
///
/// Used to tell two very different unrasterizable clips apart. A clip with
/// enormous coordinates that still *encloses* the page restricts nothing that
/// is visible, so discarding it is harmless. A clip placed far off-page
/// excludes everything, and discarding it paints the entire page that the file
/// asked to be hidden — ISO 32000-1:2008 §8.5.4 says content outside the
/// clipping path shall not be painted, and a blank page is the correct output
/// there. Annex C.1 licenses *having* an arithmetic limit; it does not license
/// resolving past one in the direction that paints more.
///
/// `None` bounds (a non-finite corner) are not "outside" — nothing can be
/// concluded about them, so they are left to the caller's fallback.
pub(crate) fn device_bounds_miss_pixmap(
    path: &tiny_skia::Path,
    transform: tiny_skia::Transform,
    width: u32,
    height: u32,
) -> bool {
    device_bounds(path, transform).is_some_and(|[min_x, min_y, max_x, max_y]| {
        max_x < 0.0 || max_y < 0.0 || min_x > f64::from(width) || min_y > f64::from(height)
    })
}

/// Whether a draw is worth handing to tiny_skia for a `width` x `height`
/// pixmap. Two independent questions that must not be conflated:
///
/// * Can the ink reach the pixmap? `device_reach` is how far the paint
///   spreads past the path itself (nothing for a fill, the outline reach for
///   a stroke). If it still misses, the draw paints nothing and dropping it
///   is free. This is the only test the untrimmed bounds are entitled to
///   fail — a box that runs off the page says nothing about whether the
///   shape covers the page, and `0 0 1e8 1e8 re f` on a 100 x 100 page
///   covers it completely.
/// * Is the path itself inside [`MAX_DEVICE_COORD`]? Past that there is
///   nothing the rasterizer can do with it. `device_reach` is deliberately
///   NOT folded in here: it is bounded separately by
///   [`MAX_DEVICE_STROKE_REACH`], and adding it would let a large CTM
///   multiply a two-unit line width into a rejection of the whole draw.
fn rasterizable_on(
    path: &tiny_skia::Path,
    transform: tiny_skia::Transform,
    device_reach: f64,
    width: u32,
    height: u32,
) -> bool {
    let Some([x0, y0, x1, y1]) = device_bounds(path, transform) else {
        return false;
    };
    if x1 + device_reach < 0.0
        || y1 + device_reach < 0.0
        || x0 - device_reach > f64::from(width)
        || y0 - device_reach > f64::from(height)
    {
        return false;
    }
    x0.abs().max(x1.abs()) <= MAX_DEVICE_COORD && y0.abs().max(y1.abs()) <= MAX_DEVICE_COORD
}

/// Uniform scale factor `transform` applies, for converting a path-space
/// line width into device units.
fn device_scale(transform: tiny_skia::Transform) -> f64 {
    let det = f64::from(transform.sx) * f64::from(transform.sy)
        - f64::from(transform.kx) * f64::from(transform.ky);
    det.abs().sqrt()
}

/// How far a stroke's outline reaches from its centerline, in path-space
/// units. tiny_skia strokes in path space before applying the transform and
/// expands the outline by up to `width/2 · miter_limit` at miter joins.
fn stroke_reach(stroke: &tiny_skia::Stroke) -> f64 {
    f64::from(stroke.width.abs()) / 2.0 * f64::from(stroke.miter_limit.max(1.0))
}

/// Narrows a stroke whose outline would reach past
/// [`MAX_DEVICE_STROKE_REACH`], returning `None` when it already fits. A
/// line that wide covers everything the pixmap can show anyway, so the width
/// is capped rather than the stroke dropped: the only pixels this changes
/// are further from the centerline than any pixmap reaches.
fn clamp_stroke_reach(
    stroke: &tiny_skia::Stroke,
    transform: tiny_skia::Transform,
) -> Option<tiny_skia::Stroke> {
    let reach = stroke_reach(stroke) * device_scale(transform);
    if !reach.is_finite() || reach <= MAX_DEVICE_STROKE_REACH {
        return None;
    }
    let mut clamped = stroke.clone();
    clamped.width = (f64::from(stroke.width.abs()) * MAX_DEVICE_STROKE_REACH / reach) as f32;
    Some(clamped)
}

/// Choke point for handing a fill to tiny_skia: skips the draw when it
/// misses the pixmap or its device-space bounds are beyond what the
/// rasterizer can carry. All content-derived fills must route through here
/// (or the mask/stroke siblings) rather than calling tiny_skia directly.
pub(crate) fn guarded_fill_path(
    pixmap: &mut tiny_skia::Pixmap,
    path: &tiny_skia::Path,
    paint: &Paint<'_>,
    fill_rule: tiny_skia::FillRule,
    transform: tiny_skia::Transform,
    clip_mask: Option<&tiny_skia::Mask>,
) {
    if !rasterizable_on(path, transform, 0.0, pixmap.width(), pixmap.height()) {
        log::debug!("skipping unrasterizable draw: {:?}", path.bounds());
        return;
    }
    pixmap.fill_path(path, paint, fill_rule, transform, clip_mask);
}

/// Stroke sibling of [`guarded_fill_path`]. A line width whose outline runs
/// past the rasterizer's reach is narrowed to one it can carry rather than
/// costing the whole stroke.
pub(crate) fn guarded_stroke_path(
    pixmap: &mut tiny_skia::Pixmap,
    path: &tiny_skia::Path,
    paint: &Paint<'_>,
    stroke: &tiny_skia::Stroke,
    transform: tiny_skia::Transform,
    clip_mask: Option<&tiny_skia::Mask>,
) {
    let clamped = clamp_stroke_reach(stroke, transform);
    let stroke = clamped.as_ref().unwrap_or(stroke);
    let reach = stroke_reach(stroke) * device_scale(transform);
    if !rasterizable_on(path, transform, reach, pixmap.width(), pixmap.height()) {
        log::debug!("skipping unrasterizable stroke: {:?}", path.bounds());
        return;
    }
    pixmap.stroke_path(path, paint, stroke, transform, clip_mask);
}

/// Mask sibling of [`guarded_fill_path`]. A skipped path leaves the mask
/// untouched, which for coverage masks means zero coverage — consistent
/// with the paint itself being skipped.
pub(crate) fn guarded_mask_fill_path(
    mask: &mut tiny_skia::Mask,
    path: &tiny_skia::Path,
    fill_rule: tiny_skia::FillRule,
    anti_alias: bool,
    transform: tiny_skia::Transform,
) {
    if !rasterizable_on(path, transform, 0.0, mask.width(), mask.height()) {
        log::debug!("skipping unrasterizable draw: {:?}", path.bounds());
        return;
    }
    mask.fill_path(path, fill_rule, anti_alias, transform);
}

/// Returns `Some(mode)` when the PDF blend mode name is one of the four
/// non-separable modes that tiny_skia cannot express natively. The
/// caller renders the paint into a fresh scratch pixmap with Normal
/// blending, then dispatches per-pixel composition via
/// [`blend_nonsep::compose_in_place`].
pub(crate) fn pdf_blend_mode_is_nonseparable(
    mode: &str,
) -> Option<blend_nonsep::NonSeparableBlend> {
    blend_nonsep::NonSeparableBlend::from_name(mode)
}

/// Run `paint` into a fresh scratch pixmap (same dimensions as `dest`)
/// with Normal blending, then per-pixel compose the scratch onto `dest`
/// using the given non-separable mode per ISO 32000-1:2008 §11.3.5.3.
///
/// `paint` is a closure that paints into the supplied scratch pixmap
/// using the rasteriser's normal code path; the closure must NOT set
/// the non-separable blend mode on its paint object (the dispatcher
/// substitutes Normal so the scratch captures only the source
/// contribution).
pub(crate) fn paint_with_nonsep_blend<F>(
    dest: &mut tiny_skia::Pixmap,
    mode: blend_nonsep::NonSeparableBlend,
    paint: F,
) where
    F: FnOnce(&mut tiny_skia::Pixmap),
{
    let w = dest.width();
    let h = dest.height();
    let mut scratch = match tiny_skia::Pixmap::new(w, h) {
        Some(p) => p,
        None => {
            // Allocation failed — fall back to direct paint (degraded
            // mode is SourceOver, which is what the legacy dispatch
            // does for non-separable modes). Better than panic.
            paint(dest);
            return;
        },
    };
    paint(&mut scratch);
    blend_nonsep::compose_in_place(dest.data_mut(), scratch.data(), mode);
}

/// Render a PDF page to an image.
///
/// This is a convenience function that creates a PageRenderer and renders
/// a single page.
///
/// # Arguments
///
/// * `doc` - The PDF document
/// * `page_num` - Zero-based page number
/// * `options` - Rendering options (DPI, format, etc.)
///
/// # Returns
///
/// The rendered image as bytes in the specified format.
pub fn render_page(
    doc: &crate::document::PdfDocument,
    page_num: usize,
    options: &RenderOptions,
) -> Result<RenderedImage> {
    let mut renderer = PageRenderer::new(options.clone());
    renderer.render_page(doc, page_num)
}

/// Render a rectangular region of a page. `crop_rect_pt` is in PDF
/// user-space points (origin bottom-left of the page). The crop is
/// applied to the fully-rendered image at the requested DPI.
pub fn render_page_region(
    doc: &crate::document::PdfDocument,
    page_num: usize,
    crop_rect_pt: (f32, f32, f32, f32),
    options: &RenderOptions,
) -> Result<RenderedImage> {
    // Full-page render first — the crop is a post-process on the
    // resulting raster. Wasteful if the crop is tiny, but matches
    // the semantics of every PDF viewer and avoids a parallel
    // clipped-raster code path in tiny-skia.
    let full = render_page(doc, page_num, options)?;

    let (crop_x_pt, crop_y_pt, crop_w_pt, crop_h_pt) = crop_rect_pt;
    if crop_w_pt <= 0.0 || crop_h_pt <= 0.0 {
        return Err(crate::Error::InvalidPdf(format!("invalid crop rect: {crop_rect_pt:?}")));
    }

    let media = doc.get_page_media_box(page_num)?;
    let page_h_pt = media.3 - media.1;

    // Points → pixels at the render DPI.
    let scale = options.dpi as f32 / 72.0;
    let crop_x_px = (crop_x_pt * scale).round().max(0.0) as u32;
    // Image Y is top-left origin; PDF Y is bottom-left. Flip.
    let top_y_pt = page_h_pt - (crop_y_pt + crop_h_pt);
    let crop_y_px = (top_y_pt * scale).round().max(0.0) as u32;
    let crop_w_px = (crop_w_pt * scale).round().max(1.0) as u32;
    let crop_h_px = (crop_h_pt * scale).round().max(1.0) as u32;

    // Decode, crop, re-encode using the `image` crate (already a dep).
    let full_img = image::load_from_memory(&full.data)
        .map_err(|e| crate::Error::InvalidPdf(format!("render output decode: {e}")))?;
    let x = crop_x_px.min(full_img.width().saturating_sub(1));
    let y = crop_y_px.min(full_img.height().saturating_sub(1));
    let w = crop_w_px.min(full_img.width() - x);
    let h = crop_h_px.min(full_img.height() - y);
    let cropped = full_img.crop_imm(x, y, w, h);

    let mut buf = Vec::new();
    match options.format {
        ImageFormat::Jpeg => {
            use image::ImageEncoder;
            let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(
                &mut buf,
                options.jpeg_quality.clamp(1, 100),
            );
            encoder
                .write_image(cropped.as_bytes(), w, h, cropped.color().into())
                .map_err(|e| crate::Error::InvalidPdf(format!("jpeg encode: {e}")))?;
        },
        _ => {
            use image::codecs::png::{CompressionType, FilterType, PngEncoder};
            use image::ImageEncoder;
            PngEncoder::new_with_quality(&mut buf, CompressionType::Fast, FilterType::Sub)
                .write_image(cropped.as_bytes(), w, h, cropped.color().into())
                .map_err(|e| crate::Error::InvalidPdf(format!("png encode: {e}")))?;
        },
    }
    Ok(RenderedImage {
        data: buf,
        width: w,
        height: h,
        format: full.format,
    })
}

/// Render a page to fit inside a target bounding box (in pixels),
/// preserving aspect ratio. Picks the DPI that makes the larger of
/// the two page dimensions match the smaller bounding-box side.
pub fn render_page_fit(
    doc: &crate::document::PdfDocument,
    page_num: usize,
    fit_w_px: u32,
    fit_h_px: u32,
    options: &RenderOptions,
) -> Result<RenderedImage> {
    if fit_w_px == 0 || fit_h_px == 0 {
        return Err(crate::Error::InvalidPdf("fit width/height must be positive".into()));
    }
    let page_info = doc.get_page_info(page_num)?;
    // `%` is a remainder and preserves sign, so a legal negative /Rotate (e.g. -90,
    // equivalent to 270 per ISO 32000-1 s7.7.3.3 Table 30) matched neither 90 nor
    // 270 below and the page rendered unrotated. rem_euclid normalizes to 0..359,
    // matching get_page_rotation's own `((raw % 360) + 360) % 360` convention.
    let rotation = page_info.rotation.rem_euclid(360);
    let (page_w_pt, page_h_pt) = if rotation == 90 || rotation == 270 {
        (page_info.media_box.height.max(1.0), page_info.media_box.width.max(1.0))
    } else {
        (page_info.media_box.width.max(1.0), page_info.media_box.height.max(1.0))
    };

    // Compute scale as a float ratio to avoid integer-DPI quantization (issue #480).
    let scale = (fit_w_px as f32 / page_w_pt).min(fit_h_px as f32 / page_h_pt);
    let mut opts = options.clone();
    opts.scale_override = Some(scale);
    render_page(doc, page_num, &opts)
}

/// Create a flattened PDF where each page is rendered as an image.
///
/// This "burns in" all annotations, form fields, overlays, and text into
/// a flat raster representation. Useful for redaction, archival, or
/// ensuring consistent visual output across viewers.
///
/// Returns the flattened PDF as bytes.
pub fn flatten_to_images(doc: &crate::document::PdfDocument, dpi: u32) -> Result<Vec<u8>> {
    let page_count = doc.page_count()?;
    let options = RenderOptions::with_dpi(dpi);

    // Render each page to PNG
    let tmp_dir = std::env::temp_dir().join(format!("pdf_oxide_flatten_{}", std::process::id()));
    std::fs::create_dir_all(&tmp_dir)?;

    let mut paths: Vec<String> = Vec::new();
    for page_idx in 0..page_count {
        let mut renderer = PageRenderer::new(options.clone());
        let rendered = renderer.render_page(doc, page_idx)?;
        let path = tmp_dir.join(format!("page_{}.png", page_idx));
        std::fs::write(&path, &rendered.data)?;
        paths.push(path.to_string_lossy().to_string());
    }

    // Build a new PDF from the rendered images
    let pdf = crate::api::Pdf::from_images(&paths)?;
    let bytes = pdf.into_bytes();

    // Cleanup
    let _ = std::fs::remove_dir_all(&tmp_dir);

    Ok(bytes)
}