unpdf-cli 0.13.0

CLI tool for extracting PDF content to Markdown, text, and JSON
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
//! unpdf CLI - PDF content extraction tool

mod update;
mod writer;

use std::fs;
use std::path::{Path, PathBuf};

use clap::{Parser, Subcommand, ValueEnum};
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};

use unpdf::{
    parse_file_with_options, CleanupPreset, JsonFormat, PageSelection, ParseOptions, RenderOptions,
};
use unpdf::{PageStreamOptions, ParseEvent, PdfParser};

/// Arguments for the `convert` subcommand.
#[derive(Parser, Debug)]
pub struct ConvertArgs {
    /// Input PDF file
    #[arg(value_name = "FILE")]
    pub input: PathBuf,

    /// Output directory
    #[arg(short, long, value_name = "DIR")]
    pub output: Option<PathBuf>,

    /// Text cleanup preset
    #[arg(long, value_enum)]
    pub cleanup: Option<CleanupLevel>,

    /// Apply the markdown shape-refinement pass (table shape, list numbering,
    /// link/image paths, frontmatter, section anchors)
    #[arg(long)]
    pub refine: bool,

    /// Output formats (comma-separated: md,txt,json)
    #[arg(long, value_delimiter = ',', default_value = "md")]
    pub formats: Vec<String>,

    /// Output all formats (MD + TXT + JSON)
    #[arg(long)]
    pub all: bool,

    /// Skip image extraction (images are extracted by default)
    #[arg(long)]
    pub no_images: bool,

    /// Keep a scan's OCR text layer even when it recognised nothing readable
    #[arg(long)]
    pub keep_ocr_text: bool,

    /// Directory for extracted images (defaults to `<out>/images`)
    #[arg(long, value_name = "DIR")]
    pub image_dir: Option<PathBuf>,

    /// Minimum pixel dimension for extracted images. Smaller images are
    /// dropped as decorative (logos, bullets, rules). 0 keeps all.
    #[arg(long, value_name = "PX", default_value = "64")]
    pub min_image_size: u32,

    /// Override streaming window size (pages in-flight)
    #[arg(long, value_name = "N")]
    pub window: Option<usize>,

    /// Insert HTML page boundary markers (<!-- page N -->)
    #[arg(long)]
    pub page_markers: bool,

    /// Suppress warning messages
    #[arg(short, long)]
    pub quiet: bool,
}

#[derive(Parser)]
#[command(name = "unpdf")]
#[command(author = "iyulab")]
#[command(version)]
#[command(about = "Extract PDF content to Markdown, text, and JSON", long_about = None)]
struct Cli {
    /// Input PDF file
    #[arg(value_name = "FILE")]
    input: Option<PathBuf>,

    /// Output directory
    #[arg(value_name = "OUTPUT")]
    output: Option<PathBuf>,

    /// Text cleanup preset
    #[arg(long, value_enum)]
    cleanup: Option<CleanupLevel>,

    /// Apply the markdown shape-refinement pass (table shape, list numbering,
    /// link/image paths, frontmatter, section anchors)
    #[arg(long)]
    refine: bool,

    /// Suppress warning messages
    #[arg(short, long)]
    quiet: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Convert PDF to Markdown, text, and/or JSON (streaming pipeline)
    Convert(ConvertArgs),

    /// Convert PDF to Markdown
    #[command(alias = "md")]
    Markdown {
        /// Input PDF file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output file (stdout if not specified)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,

        /// Include YAML frontmatter
        #[arg(short, long)]
        frontmatter: bool,

        /// Table rendering mode
        #[arg(long, value_enum, default_value = "markdown")]
        table_mode: TableMode,

        /// Text cleanup preset
        #[arg(long, value_enum)]
        cleanup: Option<CleanupLevel>,

        /// Apply the markdown shape-refinement pass (table shape, list
        /// numbering, link/image paths, frontmatter, section anchors)
        #[arg(long)]
        refine: bool,

        /// Maximum heading level (1-6)
        #[arg(long, default_value = "6")]
        max_heading: u8,

        /// Page range (e.g., "1-10", "1,3,5")
        #[arg(long)]
        pages: Option<String>,

        /// Insert HTML page boundary markers (<!-- page N -->)
        #[arg(long)]
        page_markers: bool,
    },

    /// Convert PDF to plain text
    Text {
        /// Input PDF file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output file (stdout if not specified)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,

        /// Text cleanup preset
        #[arg(long, value_enum)]
        cleanup: Option<CleanupLevel>,

        /// Accepted for API consistency with other subcommands; has no
        /// effect since plain text output is not markdown.
        #[arg(long)]
        refine: bool,

        /// Page range (e.g., "1-10", "1,3,5")
        #[arg(long)]
        pages: Option<String>,
    },

    /// Convert PDF to JSON
    Json {
        /// Input PDF file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output file (stdout if not specified)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,

        /// Output compact JSON
        #[arg(long)]
        compact: bool,
    },

    /// Show document information
    Info {
        /// Input PDF file
        #[arg(value_name = "FILE")]
        input: PathBuf,
    },

    /// Extract images from PDF
    Extract {
        /// Input PDF file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output directory
        #[arg(short, long, value_name = "DIR")]
        output: Option<PathBuf>,

        /// Page range (e.g., "1-10", "1,3,5")
        #[arg(long)]
        pages: Option<String>,
    },

    /// Self-update to latest version
    Update {
        /// Only check for updates, don't install
        #[arg(long)]
        check: bool,

        /// Force reinstall even if up-to-date
        #[arg(long)]
        force: bool,
    },

    /// Show version information
    Version,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
pub enum CleanupLevel {
    /// Minimal cleanup (Unicode normalization only)
    Minimal,
    /// Standard cleanup (default)
    Standard,
    /// Aggressive cleanup (for LLM training)
    Aggressive,
}

impl From<CleanupLevel> for CleanupPreset {
    fn from(level: CleanupLevel) -> Self {
        match level {
            CleanupLevel::Minimal => CleanupPreset::Minimal,
            CleanupLevel::Standard => CleanupPreset::Standard,
            CleanupLevel::Aggressive => CleanupPreset::Aggressive,
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
enum TableMode {
    /// Standard Markdown tables
    Markdown,
    /// HTML tables for complex layouts
    Html,
    /// ASCII art tables
    Ascii,
}

impl From<TableMode> for unpdf::TableFallback {
    fn from(mode: TableMode) -> Self {
        match mode {
            TableMode::Markdown => unpdf::TableFallback::Markdown,
            TableMode::Html => unpdf::TableFallback::Html,
            TableMode::Ascii => unpdf::TableFallback::Ascii,
        }
    }
}

/// Check extraction quality and print warnings to stderr.
/// Returns true if quality warnings were emitted.
fn check_quality(doc: &unpdf::Document, quiet: bool) -> bool {
    if quiet {
        return false;
    }
    if let Some(warning) = doc.extraction_quality.warning_message() {
        eprintln!("{}: {}", "Warning".yellow().bold(), warning);
        return true;
    }
    false
}

/// Check if we should perform background update check.
/// Skip for update/version commands to avoid redundant checks.
fn should_check_update(cli: &Cli) -> bool {
    !matches!(
        &cli.command,
        Some(Commands::Update { .. }) | Some(Commands::Version)
    )
}

fn main() {
    env_logger::init();

    let cli = Cli::parse();

    // Start background update check (except for update/version commands)
    let update_rx = if should_check_update(&cli) {
        Some(update::check_update_async())
    } else {
        None
    };

    let quiet = cli.quiet;

    let result = match cli.command {
        Some(Commands::Convert(mut args)) => {
            // Top-level --quiet propagates into ConvertArgs
            if quiet {
                args.quiet = true;
            }
            cmd_convert(&args)
        }
        Some(Commands::Markdown {
            input,
            output,
            frontmatter,
            table_mode,
            cleanup,
            refine,
            max_heading,
            pages,
            page_markers,
        }) => cmd_markdown(
            &input,
            output.as_deref(),
            frontmatter,
            table_mode,
            cleanup,
            refine,
            max_heading,
            pages.as_deref(),
            page_markers,
            quiet,
        ),
        Some(Commands::Text {
            input,
            output,
            cleanup,
            refine,
            pages,
        }) => {
            let _ = refine;
            cmd_text(&input, output.as_deref(), cleanup, pages.as_deref(), quiet)
        }
        Some(Commands::Json {
            input,
            output,
            compact,
        }) => cmd_json(&input, output.as_deref(), compact, quiet),
        Some(Commands::Info { input }) => cmd_info(&input, quiet),
        Some(Commands::Extract {
            input,
            output,
            pages,
        }) => cmd_extract(&input, output.as_deref(), pages.as_deref(), quiet),
        Some(Commands::Update { check, force }) => {
            if let Err(e) = update::run_update(check, force) {
                eprintln!("{}: {}", "Error".red().bold(), e);
                std::process::exit(1);
            }
            Ok(false)
        }
        Some(Commands::Version) => {
            cmd_version();
            Ok(false)
        }
        None => {
            // Default behavior: convert if input is provided
            if let Some(input) = cli.input {
                let args = ConvertArgs {
                    input,
                    output: cli.output,
                    cleanup: cli.cleanup,
                    refine: cli.refine,
                    formats: vec!["md".to_string()],
                    all: false,
                    no_images: false,
                    keep_ocr_text: false,
                    image_dir: None,
                    min_image_size: 64,
                    window: None,
                    page_markers: false,
                    quiet,
                };
                cmd_convert(&args)
            } else {
                println!("{}", "Usage: unpdf <FILE> [OUTPUT]".yellow());
                println!("       unpdf --help for more information");
                Ok(false)
            }
        }
    };

    // Check for update result and show notification if available
    if let Some(rx) = update_rx {
        if let Some(update_result) = update::try_get_update_result(&rx) {
            update::print_update_notification(&update_result);
        }
    }

    match result {
        Ok(had_warnings) => {
            if had_warnings {
                std::process::exit(2);
            }
        }
        Err(e) => {
            eprintln!("{}: {}", "Error".red().bold(), e);
            std::process::exit(1);
        }
    }
}

fn cmd_convert(args: &ConvertArgs) -> Result<bool, Box<dyn std::error::Error>> {
    use std::ops::ControlFlow;

    let out_dir = args.output.clone().unwrap_or_else(|| {
        let stem = args.input.file_stem().unwrap_or_default().to_string_lossy();
        PathBuf::from(format!("{}_output", stem))
    });
    fs::create_dir_all(&out_dir)?;

    // Determine output formats
    let formats: Vec<writer::OutputFormat> = if args.all {
        vec![
            writer::OutputFormat::Markdown,
            writer::OutputFormat::Text,
            writer::OutputFormat::Json,
        ]
    } else {
        let mut v: Vec<_> = args
            .formats
            .iter()
            .filter_map(|s| match s.as_str() {
                "md" | "markdown" => Some(writer::OutputFormat::Markdown),
                "txt" | "text" => Some(writer::OutputFormat::Text),
                "json" => Some(writer::OutputFormat::Json),
                other => {
                    eprintln!("warning: unknown format: {}", other);
                    None
                }
            })
            .collect();
        if v.is_empty() {
            v.push(writer::OutputFormat::Markdown);
        }
        v
    };

    // Image extraction configuration — 기본 on. `--no-images` 로 옵트아웃.
    // `--image-dir` 지정 시 그 경로가 우선, 없으면 `<out>/images` 사용.
    // 디렉토리는 첫 이미지가 실제로 쓰일 때만 생성 (이미지 없는 PDF 에서
    // 빈 폴더가 남는 것 방지) — MultiFormatWriter 내부에서 처리.
    let image_dir: Option<PathBuf> = if args.no_images {
        None
    } else {
        Some(
            args.image_dir
                .clone()
                .unwrap_or_else(|| out_dir.join("images")),
        )
    };

    // Build render options
    let mut render_opts = RenderOptions::new().with_frontmatter(true);
    if image_dir.is_some() {
        render_opts = render_opts.with_image_prefix("images/");
    }
    if let Some(level) = args.cleanup {
        render_opts = render_opts.with_cleanup_preset(level.into());
    }
    if args.refine {
        render_opts = render_opts.with_refine();
    }
    if args.page_markers {
        render_opts = render_opts.with_page_markers(unpdf::PageMarkerStyle::Comment);
    }

    // Open parser
    let mut parse_options = ParseOptions::new()
        .lenient()
        .with_ocr_suppression(!args.keep_ocr_text);
    if image_dir.is_some() {
        parse_options = parse_options.with_resources(true);
    }
    let parser = PdfParser::open_with_options(&args.input, parse_options)?;

    // Set up writer
    let mut mfw =
        writer::MultiFormatWriter::new(&out_dir, &formats, render_opts, image_dir.clone())?;

    // Stream options
    let mut stream_opts = PageStreamOptions {
        extract_resources: image_dir.is_some(),
        min_image_dimension: args.min_image_size,
        suppress_low_confidence_ocr: !args.keep_ocr_text,
        ..PageStreamOptions::default()
    };
    if let Some(w) = args.window {
        stream_opts.window_size = w.max(1);
    }

    // Progress bar
    let total_pages = parser.page_count();
    let pb = if args.quiet {
        ProgressBar::hidden()
    } else {
        let b = ProgressBar::new(total_pages as u64);
        b.set_style(
            ProgressStyle::default_bar()
                .template("{bar:40.cyan/blue} {pos}/{len} pages ({eta})")
                .unwrap(),
        );
        b
    };

    let mut quality = None;
    let mut write_err: Option<String> = None;

    parser.for_each_page(stream_opts, |ev| {
        match ev {
            ParseEvent::DocumentStart {
                metadata,
                page_count,
                ..
            } => {
                if let Err(e) = mfw.write_document_start(&metadata, page_count) {
                    write_err = Some(format!("document start: {}", e));
                    return ControlFlow::Break(());
                }
            }
            ParseEvent::PageParsed(mut page) => {
                if let Err(e) = mfw.write_page(&mut page) {
                    write_err = Some(format!("page {}: {}", page.number, e));
                    return ControlFlow::Break(());
                }
                pb.inc(1);
            }
            ParseEvent::PageFailed { page, error } => {
                eprintln!("page {} failed: {}", page, error);
                pb.inc(1);
            }
            ParseEvent::DocumentEnd { quality: q } => {
                quality = Some(q);
            }
            ParseEvent::Progress { .. } => {}
        }
        ControlFlow::Continue(())
    })?;

    if let Some(e) = write_err {
        return Err(e.into());
    }

    let summary = mfw.finish()?;
    pb.finish_with_message("Done");

    if !args.quiet {
        for path in [&summary.md_path, &summary.txt_path, &summary.json_path]
            .into_iter()
            .flatten()
        {
            println!("{} {}", "✓".green(), path.display());
        }
        if summary.image_count > 0 {
            let img_dir = image_dir.as_deref().unwrap_or_else(|| Path::new("images"));
            println!(
                "{} {} image{} → {}",
                "✓".green(),
                summary.image_count,
                if summary.image_count == 1 { "" } else { "s" },
                img_dir.display()
            );
        }
        if summary.word_count > 0 {
            println!("{} {} words", "✓".green(), summary.word_count);
        }
    }

    let warning = quality.as_ref().and_then(|q| q.warning_message());
    if let Some(warning) = &warning {
        if !args.quiet {
            eprintln!("{}: {}", "Warning".yellow().bold(), warning);
        }
    }
    Ok(warning.is_some())
}

#[allow(clippy::too_many_arguments)]
fn cmd_markdown(
    input: &Path,
    output: Option<&Path>,
    frontmatter: bool,
    table_mode: TableMode,
    cleanup: Option<CleanupLevel>,
    refine: bool,
    max_heading: u8,
    pages: Option<&str>,
    page_markers: bool,
    quiet: bool,
) -> Result<bool, Box<dyn std::error::Error>> {
    let page_selection = if let Some(p) = pages {
        PageSelection::parse(p).map_err(|e| format!("Invalid page range: {}", e))?
    } else {
        PageSelection::All
    };

    // Use lenient mode to continue even if some text extraction fails
    let options = ParseOptions::new()
        .lenient()
        .with_pages(page_selection.clone());
    let doc = parse_file_with_options(input, options)?;
    let had_warnings = check_quality(&doc, quiet);

    let mut render_options = RenderOptions::new()
        .with_frontmatter(frontmatter)
        .with_table_fallback(table_mode.into())
        .with_max_heading(max_heading)
        .with_pages(page_selection);

    if page_markers {
        render_options = render_options.with_page_markers(unpdf::PageMarkerStyle::Comment);
    }

    if let Some(level) = cleanup {
        render_options = render_options.with_cleanup_preset(level.into());
    }
    if refine {
        render_options = render_options.with_refine();
    }

    let markdown = unpdf::render::to_markdown(&doc, &render_options)?;

    if let Some(path) = output {
        fs::write(path, &markdown)?;
        println!("{} {}", "Saved to".green(), path.display());
    } else {
        println!("{}", markdown);
    }

    Ok(had_warnings)
}

fn cmd_text(
    input: &Path,
    output: Option<&Path>,
    cleanup: Option<CleanupLevel>,
    pages: Option<&str>,
    quiet: bool,
) -> Result<bool, Box<dyn std::error::Error>> {
    let page_selection = if let Some(p) = pages {
        PageSelection::parse(p).map_err(|e| format!("Invalid page range: {}", e))?
    } else {
        PageSelection::All
    };

    // Use lenient mode to continue even if some text extraction fails
    let options = ParseOptions::new().lenient().with_pages(page_selection);
    let doc = parse_file_with_options(input, options)?;
    let had_warnings = check_quality(&doc, quiet);

    let mut render_options = RenderOptions::new();
    if let Some(level) = cleanup {
        render_options = render_options.with_cleanup_preset(level.into());
    }

    let text = unpdf::render::to_text(&doc, &render_options)?;

    if let Some(path) = output {
        fs::write(path, &text)?;
        println!("{} {}", "Saved to".green(), path.display());
    } else {
        println!("{}", text);
    }

    Ok(had_warnings)
}

fn cmd_json(
    input: &Path,
    output: Option<&Path>,
    compact: bool,
    quiet: bool,
) -> Result<bool, Box<dyn std::error::Error>> {
    // Use lenient mode to continue even if some text extraction fails
    let options = ParseOptions::new().lenient();
    let doc = unpdf::parse_file_with_options(input, options)?;
    let had_warnings = check_quality(&doc, quiet);

    let format = if compact {
        JsonFormat::Compact
    } else {
        JsonFormat::Pretty
    };

    let json = unpdf::render::to_json(&doc, format)?;

    if let Some(path) = output {
        fs::write(path, &json)?;
        println!("{} {}", "Saved to".green(), path.display());
    } else {
        println!("{}", json);
    }

    Ok(had_warnings)
}

fn cmd_info(input: &Path, quiet: bool) -> Result<bool, Box<dyn std::error::Error>> {
    // Use lenient mode for info command - we want to show metadata even if text extraction fails
    let options = ParseOptions::new().lenient();
    let doc = parse_file_with_options(input, options)?;
    let had_warnings = check_quality(&doc, quiet);

    println!("{}", "Document Information".cyan().bold());
    println!("{}", "─".repeat(40).dimmed());

    println!("{}: {}", "File".bold(), input.display());
    println!("{}: PDF {}", "Format".bold(), doc.metadata.pdf_version);
    // Report page loss on the Pages line itself, not only through the quality warning:
    // `--quiet` silences warnings, and a diagnostic command must not hide a short page
    // set just because the caller asked for less noise.
    let q = &doc.extraction_quality;
    match (q.pages_incomplete, q.declared_page_count) {
        (true, Some(declared)) => println!(
            "{}: {} {}",
            "Pages".bold(),
            doc.metadata.page_count,
            format!("(incomplete — document declares {})", declared).yellow()
        ),
        (true, None) => println!(
            "{}: {} {}",
            "Pages".bold(),
            doc.metadata.page_count,
            "(incomplete — page structure damaged)".yellow()
        ),
        _ => println!("{}: {}", "Pages".bold(), doc.metadata.page_count),
    }
    // Same reasoning as the Pages line above: text the decoder could not read is
    // content missing from the output, and `--quiet` would silence the warning that
    // otherwise carries it. Printed only when non-zero — an intact document should
    // not have to read a line saying nothing was lost.
    if q.suppressed_text_runs > 0 {
        println!(
            "{}: {}",
            "Text runs".bold(),
            format!(
                "{} unreadable, dropped (fonts' character codes unresolved)",
                q.suppressed_text_runs
            )
            .yellow()
        );
    }
    println!(
        "{}: {}",
        "Encrypted".bold(),
        if doc.metadata.encrypted { "Yes" } else { "No" }
    );

    if let Some(ref title) = doc.metadata.title {
        println!("{}: {}", "Title".bold(), title);
    }
    if let Some(ref author) = doc.metadata.author {
        println!("{}: {}", "Author".bold(), author);
    }
    if let Some(ref creator) = doc.metadata.creator {
        println!("{}: {}", "Creator".bold(), creator);
    }
    if let Some(ref producer) = doc.metadata.producer {
        println!("{}: {}", "Producer".bold(), producer);
    }
    if let Some(ref created) = doc.metadata.created {
        println!("{}: {}", "Created".bold(), created);
    }
    if let Some(ref modified) = doc.metadata.modified {
        println!("{}: {}", "Modified".bold(), modified);
    }

    println!();
    println!("{}", "Content Statistics".cyan().bold());
    println!("{}", "─".repeat(40).dimmed());

    let text = doc.plain_text();
    let words: usize = text.split_whitespace().count();
    let chars = text.len();
    let images = doc.resources.values().filter(|r| r.is_image()).count();

    println!("{}: {}", "Words".bold(), words);
    println!("{}: {}", "Characters".bold(), chars);
    println!("{}: {}", "Images".bold(), images);

    if let Some(ref outline) = doc.outline {
        println!("{}: {}", "Bookmarks".bold(), outline.total_items());
    }

    Ok(had_warnings)
}

fn cmd_extract(
    input: &Path,
    output: Option<&Path>,
    pages: Option<&str>,
    quiet: bool,
) -> Result<bool, Box<dyn std::error::Error>> {
    let page_selection = if let Some(p) = pages {
        PageSelection::parse(p).map_err(|e| format!("Invalid page range: {}", e))?
    } else {
        PageSelection::All
    };

    // Use lenient mode to continue even if some text extraction fails
    let options = ParseOptions::new().lenient().with_pages(page_selection);
    let doc = parse_file_with_options(input, options)?;
    let had_warnings = check_quality(&doc, quiet);

    let output_dir = output
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| PathBuf::from("."));
    fs::create_dir_all(&output_dir)?;

    let mut count = 0;
    for (id, resource) in &doc.resources {
        if resource.is_image() {
            let filename = resource.suggested_filename(id);
            let path = output_dir.join(&filename);
            fs::write(&path, &resource.data)?;
            println!("{} {}", "Extracted".green(), filename);
            count += 1;
        }
    }

    println!("\n{} {} images extracted", "Done!".green().bold(), count);

    Ok(had_warnings)
}

fn cmd_version() {
    println!("{} {}", "unpdf".cyan().bold(), env!("CARGO_PKG_VERSION"));
    println!("PDF content extraction tool");
    println!();
    println!("Repository: {}", "https://github.com/iyulab/unpdf".dimmed());
    println!("License: MIT");
}