markdown2pdf 0.3.0

Create PDF with Markdown files (a md to pdf transpiler)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! PDF generation module for markdown-to-pdf conversion.
//!
//! This module handles the complete process of converting parsed markdown content into professionally formatted PDF documents.
//! It provides robust support for generating PDFs with proper typography, layout, and styling while maintaining the semantic
//! structure of the original markdown.
//!
//! The PDF generation process preserves the hierarchical document structure through careful handling of block-level and inline
//! elements. Block elements like headings, paragraphs, lists and code blocks are rendered with appropriate spacing and indentation.
//! Inline formatting such as emphasis, links and inline code maintain proper nesting and style inheritance.
//!
//! The styling system offers extensive customization options through a flexible configuration model. This includes control over:
//! fonts, text sizes, colors, margins, spacing, and special styling for different content types. The module automatically handles
//! font loading, page layout, and proper rendering of all markdown elements while respecting the configured styles.
//!
//! Error handling is built in throughout the generation process to provide meaningful feedback if issues occur during PDF creation.
//! The module is designed to be both robust for production use and flexible enough to accommodate various document structures
//! and styling needs.

use crate::{styling::StyleMatch, Token};
use genpdfi::{
    fonts::{FontData, FontFamily},
    Alignment, Document,
};
use log::warn;

/// The main PDF document generator that orchestrates the conversion process from markdown to PDF.
/// This struct serves as the central coordinator for document generation, managing the overall
/// structure, styling application, and proper sequencing of content elements.
/// It stores the input markdown tokens that will be processed into PDF content, along with style
/// configuration that controls the visual appearance and layout of the generated document.
/// The generator maintains two separate font families - a main text font used for regular document
/// content and a specialized monospace font specifically for code sections.
/// These fonts are loaded based on the style configuration and stored internally for use during
/// the PDF generation process.
pub struct Pdf {
    input: Vec<Token>,
    style: StyleMatch,
    font_family: FontFamily<FontData>,
    #[allow(dead_code)] // Reserved for future code block font support
    code_font_family: FontFamily<FontData>,
}

/// Style flags toggled by raw inline HTML tags during paragraph rendering.
/// `<b>`/`<strong>` → bold, `<i>`/`<em>` → italic, `<u>` → underline,
/// `<s>`/`<del>` → strikethrough. Closing tags clear the flag. Unknown
/// tags don't touch the flags and are rendered as literal text instead.
#[derive(Clone, Default)]
struct HtmlInlineFlags {
    bold: bool,
    italic: bool,
    underline: bool,
    strikethrough: bool,
}

impl HtmlInlineFlags {
    fn apply(&self, mut style: genpdfi::style::Style) -> genpdfi::style::Style {
        if self.bold {
            style = style.bold();
        }
        if self.italic {
            style = style.italic();
        }
        if self.underline {
            style = style.underline();
        }
        if self.strikethrough {
            style = style.strikethrough();
        }
        style
    }
}

#[derive(Clone, Copy)]
enum HtmlFlag {
    Bold,
    Italic,
    Underline,
    Strikethrough,
}

#[derive(Clone, Copy)]
enum HtmlTagAction {
    Toggle(HtmlFlag, bool),
    SoftBreak,
}

/// Maps a raw `<tag>` (or `</tag>`, `<br/>`) to the renderer action it
/// triggers. Returns `None` for tags that should pass through as literal
/// text (preserving the current behavior for unrecognized HTML).
fn classify_html_tag(tag: &str) -> Option<HtmlTagAction> {
    let stripped = tag.trim_start_matches('<').trim_end_matches('>');
    let (is_close, name) = if let Some(rest) = stripped.strip_prefix('/') {
        (true, rest)
    } else {
        (false, stripped)
    };
    // Strip `/` from `<tag/>` self-close form, plus any attributes after the tag name.
    let name = name.trim_end_matches('/').trim();
    let tag_name: String = name
        .split(|c: char| c.is_whitespace() || c == '/')
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();
    match tag_name.as_str() {
        "b" | "strong" => Some(HtmlTagAction::Toggle(HtmlFlag::Bold, !is_close)),
        "i" | "em" => Some(HtmlTagAction::Toggle(HtmlFlag::Italic, !is_close)),
        "u" => Some(HtmlTagAction::Toggle(HtmlFlag::Underline, !is_close)),
        "s" | "del" | "strike" => Some(HtmlTagAction::Toggle(HtmlFlag::Strikethrough, !is_close)),
        "br" => Some(HtmlTagAction::SoftBreak),
        _ => None,
    }
}

impl Pdf {
    /// Creates a new PDF generator instance to process markdown tokens.
    ///
    /// Loads two font families based on configuration:
    /// - Main text font for regular content
    /// - Code font for code blocks and inline code
    ///
    /// # Arguments
    /// * `input` - The markdown tokens to convert
    /// * `style` - Style configuration for the document
    /// * `font_config` - Optional font configuration
    pub fn new(
        input: Vec<Token>,
        style: StyleMatch,
        font_config: Option<&crate::fonts::FontConfig>,
    ) -> Result<Self, crate::MdpError> {
        // Get the requested font name
        let family_name = font_config
            .and_then(|cfg| cfg.default_font.as_deref())
            .or(style.text.font_family)
            .unwrap_or("Helvetica");

        // Check if this is a built-in PDF font (fast path)
        let is_builtin = matches!(
            family_name.to_lowercase().as_str(),
            "helvetica"
                | "arial"
                | "sans-serif"
                | "times"
                | "times new roman"
                | "serif"
                | "courier"
                | "courier new"
                | "monospace"
        );

        let font_err = |name: &str, e: &dyn std::fmt::Display| crate::MdpError::FontError {
            font_name: name.to_string(),
            message: e.to_string(),
            suggestion: "Ensure font files are accessible or use a built-in font (Helvetica, Times, Courier).".to_string(),
        };

        // Load main font
        let font_family = if let Some(source) =
            font_config.and_then(|c| c.default_font_source.clone())
        {
            match crate::fonts::load_font_family(source) {
                Ok(font) => font,
                Err(e) => {
                    warn!("Could not load font from source: {}. Using Helvetica.", e);
                    crate::fonts::load_builtin_font_family("Helvetica")
                        .map_err(|e| font_err("Helvetica", &e))?
                }
            }
        } else if is_builtin {
            // Fast path: built-in fonts need no file I/O for rendering
            crate::fonts::load_builtin_font_family(family_name)
                .map_err(|e| font_err(family_name, &e))?
        } else {
            // Custom font: collect text for subsetting if enabled
            let text = if font_config.map(|c| c.enable_subsetting).unwrap_or(true) {
                Some(Token::collect_all_text(&input))
            } else {
                None
            };

            match crate::fonts::load_font(family_name, font_config, text.as_deref()) {
                Ok(font) => font,
                Err(e) => {
                    warn!(
                        "Could not load font '{}': {}. Using Helvetica.",
                        family_name, e
                    );
                    crate::fonts::load_builtin_font_family("Helvetica")
                        .map_err(|e| font_err("Helvetica", &e))?
                }
            }
        };

        // Load code font (built-in Courier is fastest)
        let code_font_name = font_config
            .and_then(|cfg| cfg.code_font.as_deref())
            .unwrap_or("Courier");

        let code_font_family = if let Some(source) =
            font_config.and_then(|c| c.code_font_source.clone())
        {
            match crate::fonts::load_font_family(source) {
                Ok(font) => font,
                Err(e) => {
                    warn!("Could not load code font from source: {}. Using Courier.", e);
                    crate::fonts::load_builtin_font_family("Courier")
                        .map_err(|e| font_err("Courier", &e))?
                }
            }
        } else {
            match crate::fonts::load_builtin_font_family(code_font_name) {
                Ok(font) => font,
                Err(_) => crate::fonts::load_builtin_font_family("Courier")
                    .map_err(|e| font_err("Courier", &e))?,
            }
        };

        Ok(Self {
            input,
            style,
            font_family,
            code_font_family,
        })
    }

    /// Finalizes and outputs the processed document to a PDF file at the specified path.
    /// Provides comprehensive error handling to catch and report any issues during the
    /// final rendering phase.
    pub fn render(document: genpdfi::Document, path: &str) -> Option<String> {
        match document.render_to_file(path) {
            Ok(_) => None,
            Err(err) => Some(err.to_string()),
        }
    }

    /// Renders the processed document to bytes and returns the PDF data as a Vec<u8>.
    /// This method provides the same PDF generation as `render` but returns the content
    /// directly as bytes instead of writing to a file, making it suitable for cases
    /// where you need to handle the PDF data in memory or send it over a network.
    ///
    /// # Arguments
    /// * `document` - The generated PDF document to render
    ///
    /// # Returns
    /// * `Ok(Vec<u8>)` containing the PDF data on successful rendering
    /// * `Err(String)` with error message if rendering fails
    ///
    /// # Example
    /// ```rust
    /// // This example shows the basic usage pattern, but render_to_bytes
    /// // is typically called internally by parse_into_bytes
    /// use markdown2pdf::{parse_into_bytes, config::ConfigSource};
    ///
    /// let markdown = "# Test\nSome content".to_string();
    /// let pdf_bytes = parse_into_bytes(markdown, ConfigSource::Default, None).unwrap();
    /// // Use the bytes as needed (save, send, etc.)
    /// assert!(!pdf_bytes.is_empty());
    /// ```
    pub fn render_to_bytes(document: genpdfi::Document) -> Result<Vec<u8>, String> {
        let mut buffer = std::io::Cursor::new(Vec::new());
        match document.render(&mut buffer) {
            Ok(_) => Ok(buffer.into_inner()),
            Err(err) => Err(err.to_string()),
        }
    }

    /// Initializes and returns a new PDF document with configured styling and layout.
    ///
    /// Creates a new document instance with the main font family and configures the page decorator
    /// with margins from the style settings. The document's base font size is set according to the
    /// text style configuration.
    ///
    /// The function processes all input tokens and renders them into the document structure before
    /// returning the complete document ready for final output. The document contains all content
    /// with proper styling, formatting and layout applied according to the style configuration.
    ///
    /// Through the style configuration, this method controls the overall document appearance including:
    /// - Page margins and layout
    /// - Base font size
    /// - Content processing and rendering
    pub fn render_into_document(&self) -> Document {
        let mut doc = genpdfi::Document::new(self.font_family.clone());
        let mut decorator = genpdfi::SimplePageDecorator::new();

        decorator.set_margins(genpdfi::Margins::trbl(
            self.style.margins.top,
            self.style.margins.right,
            self.style.margins.bottom,
            self.style.margins.left,
        ));

        doc.set_page_decorator(decorator);
        doc.set_font_size(self.style.text.size);

        self.process_tokens(&mut doc);
        doc
    }

    /// Processes and renders tokens directly into the document structure.
    ///
    /// This method iterates through all input tokens and renders them into the document,
    /// handling each token type appropriately according to its semantic meaning. Block-level
    /// elements like headings, list items, and code blocks trigger the flushing of any
    /// accumulated inline tokens into paragraphs before being rendered themselves.
    ///
    /// The method maintains a buffer of current tokens that gets flushed into paragraphs
    /// when block-level elements are encountered or when explicit paragraph breaks are
    /// needed. This ensures proper document flow and maintains correct spacing between
    /// different content elements while preserving the intended document structure.
    ///
    /// Through careful token processing and rendering, this method builds up the complete
    /// document content with appropriate styling, formatting and layout applied according
    /// to the configured style settings.
    fn process_tokens(&self, doc: &mut Document) {
        let mut current_tokens = Vec::new();
        let mut i = 0usize;
        while i < self.input.len() {
            let token = &self.input[i];
            // CommonMark §4.8 / §6.8: a *blank* line (two or more
            // consecutive Newlines) terminates a paragraph; a single Newline
            // is a soft break and stays inside the current paragraph.
            if let Token::Newline = token {
                let mut run = 0usize;
                while i + run < self.input.len()
                    && matches!(self.input[i + run], Token::Newline)
                {
                    run += 1;
                }
                if run >= 2 {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                } else {
                    current_tokens.push(Token::Newline);
                }
                i += run;
                continue;
            }
            match token {
                Token::Heading(content, level) => {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                    self.render_heading(doc, content, *level);
                }
                Token::ListItem {
                    content,
                    ordered,
                    number,
                    checked,
                } => {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                    self.render_list_item(doc, content, *ordered, *number, *checked, 0);
                }
                Token::Code(lang, content) if content.contains('\n') => {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                    self.render_code_block(doc, lang, content);
                }
                Token::HorizontalRule => {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                    doc.push(genpdfi::elements::Break::new(
                        self.style.horizontal_rule.after_spacing,
                    ));
                }
                Token::BlockQuote(body) => {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                    self.render_blockquote(doc, body);
                }
                Token::HardBreak => {
                    // Flush current paragraph and force a line break — the
                    // visual effect for a hard break in our renderer is the
                    // same as a paragraph boundary at the moment.
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                }
                Token::Table {
                    headers,
                    aligns,
                    rows,
                } => {
                    self.flush_paragraph(doc, &current_tokens);
                    current_tokens.clear();
                    self.render_table(doc, headers, aligns, rows)
                }
                _ => {
                    current_tokens.push(token.clone());
                }
            }
            i += 1;
        }

        // Flush any remaining tokens
        self.flush_paragraph(doc, &current_tokens);
    }

    /// Renders accumulated tokens as a paragraph in the document.
    ///
    /// This method takes a document and a slice of tokens, and renders them as a paragraph
    /// with appropriate styling. If the tokens slice is empty, no paragraph is rendered.
    /// After rendering the paragraph content, it adds spacing after the paragraph according
    /// to the configured text style.
    fn flush_paragraph(&self, doc: &mut Document, tokens: &[Token]) {
        if tokens.is_empty() {
            return;
        }

        doc.push(genpdfi::elements::Break::new(
            self.style.text.before_spacing,
        ));
        let mut para = genpdfi::elements::Paragraph::default();
        self.render_inline_content(&mut para, tokens);
        doc.push(para);
        doc.push(genpdfi::elements::Break::new(self.style.text.after_spacing));
    }

    /// Renders a heading with the appropriate level styling.
    ///
    /// This method takes a document, heading content tokens, and a level number to render
    /// a heading with the corresponding style settings. It applies font size, bold/italic effects,
    /// and text color based on the heading level configuration. After rendering the heading,
    /// it adds the configured spacing.
    fn render_heading(&self, doc: &mut Document, content: &[Token], level: usize) {
        let heading_style = match level {
            1 => &self.style.heading_1,
            2 => &self.style.heading_2,
            _ => &self.style.heading_3,
        };
        doc.push(genpdfi::elements::Break::new(heading_style.before_spacing));

        let mut para = genpdfi::elements::Paragraph::default();
        // For h4–h6, derive a smaller size from heading_3 to give visual
        // hierarchy without adding new style fields. h3 is unchanged.
        let size = if level >= 4 {
            let drop = (level as u8).saturating_sub(3);
            heading_style.size.saturating_sub(drop).max(8)
        } else {
            heading_style.size
        };
        let mut style = genpdfi::style::Style::new().with_font_size(size);

        if heading_style.bold {
            style = style.bold();
        }
        if heading_style.italic {
            style = style.italic();
        }
        if let Some(color) = heading_style.text_color {
            style = style.with_color(genpdfi::style::Color::Rgb(color.0, color.1, color.2));
        }

        self.render_inline_content_with_style(&mut para, content, style);
        doc.push(para);
        doc.push(genpdfi::elements::Break::new(heading_style.after_spacing));
    }

    /// Renders inline content with a specified style.
    ///
    /// This method processes a sequence of inline tokens and renders them with the given style.
    /// It handles various inline elements like plain text, emphasis, strong emphasis, links, and
    /// inline code, applying appropriate styling modifications for each type while maintaining
    /// the base style properties.
    fn render_inline_content_with_style(
        &self,
        para: &mut genpdfi::elements::Paragraph,
        tokens: &[Token],
        style: genpdfi::style::Style,
    ) {
        let mut html_state = HtmlInlineFlags::default();
        self.render_inline_content_with_state(para, tokens, style, &mut html_state);
    }

    /// Inline renderer with mutable HTML-tag style flags. Recognized tags
    /// (`<b>`, `<strong>`, `<i>`, `<em>`, `<u>`, `<s>`, `<del>`) toggle the
    /// corresponding flag on opener / off on closer; `<br>` / `<br/>` emits
    /// a soft space. Subsequent `Token::Text` is rendered with the active
    /// flags applied to the base `style`.
    fn render_inline_content_with_state(
        &self,
        para: &mut genpdfi::elements::Paragraph,
        tokens: &[Token],
        style: genpdfi::style::Style,
        html: &mut HtmlInlineFlags,
    ) {
        for token in tokens {
            match token {
                Token::Text(content) => {
                    let s = html.apply(style.clone());
                    para.push_styled(content.clone(), s);
                }
                Token::Emphasis { level, content } => {
                    let mut nested_style = style.clone();
                    match level {
                        1 => nested_style = nested_style.italic(),
                        2 => nested_style = nested_style.bold(),
                        _ => nested_style = nested_style.bold().italic(),
                    }
                    self.render_inline_content_with_state(para, content, nested_style, html);
                }
                Token::StrongEmphasis(content) => {
                    let nested_style = style.clone().bold();
                    self.render_inline_content_with_state(para, content, nested_style, html);
                }
                Token::Link(text, url) => {
                    let mut link_style = style.clone();
                    if let Some(color) = self.style.link.text_color {
                        link_style = link_style
                            .with_color(genpdfi::style::Color::Rgb(color.0, color.1, color.2));
                    }
                    if self.style.link.bold {
                        link_style = link_style.bold();
                    }
                    if self.style.link.italic {
                        link_style = link_style.italic();
                    }
                    if self.style.link.underline {
                        link_style = link_style.underline();
                    }
                    if self.style.link.strikethrough {
                        link_style = link_style.strikethrough();
                    }
                    para.push_link(text.clone(), url.clone(), link_style);
                }
                Token::Code(_, content) => {
                    let mut code_style = style.clone();
                    if let Some(color) = self.style.code.text_color {
                        code_style = code_style
                            .with_color(genpdfi::style::Color::Rgb(color.0, color.1, color.2));
                    }
                    para.push_styled(content.clone(), code_style);
                }
                Token::Strikethrough(content) => {
                    let strike_style = style.clone().strikethrough();
                    self.render_inline_content_with_state(para, content, strike_style, html);
                }
                Token::Image(alt, url) => {
                    // genpdfi doesn't embed images yet. Render the image as
                    // a styled link so the alt-text is a clean clickable
                    // label and the underline sits cleanly underneath it.
                    let label = if alt.is_empty() {
                        url.clone()
                    } else {
                        alt.clone()
                    };
                    if !url.is_empty() {
                        let mut link_style = style.clone();
                        if let Some(color) = self.style.link.text_color {
                            link_style = link_style.with_color(
                                genpdfi::style::Color::Rgb(color.0, color.1, color.2),
                            );
                        }
                        if self.style.link.underline {
                            link_style = link_style.underline();
                        }
                        para.push_link(label, url.clone(), link_style);
                    } else {
                        para.push_styled(label, style.clone());
                    }
                }
                Token::HtmlInline(tag) => match classify_html_tag(tag) {
                    Some(HtmlTagAction::Toggle(flag, on)) => match flag {
                        HtmlFlag::Bold => html.bold = on,
                        HtmlFlag::Italic => html.italic = on,
                        HtmlFlag::Underline => html.underline = on,
                        HtmlFlag::Strikethrough => html.strikethrough = on,
                    },
                    Some(HtmlTagAction::SoftBreak) => {
                        // `<br/>` is a no-op inside an inline run — the
                        // surrounding text already provides whitespace.
                        // Inline-level forced linebreaks aren't expressible
                        // via genpdfi's Paragraph; users wanting a real
                        // break should use blank lines or two trailing
                        // spaces (hard break).
                    }
                    None => {
                        // Unknown tag — fall back to literal text.
                        para.push_styled(tag.clone(), style.clone());
                    }
                },
                Token::HardBreak => {
                    // A hard break inside inline content (e.g. inside a list
                    // item or blockquote body). genpdfi paragraphs don't
                    // expose a forced linefeed, so render as a space — the
                    // block-level path handles paragraph-boundary breaks.
                    para.push_styled(" ".to_string(), style.clone());
                }
                Token::Newline => {
                    // Soft break inside a paragraph: render as a space so
                    // multi-line paragraphs flow naturally.
                    para.push_styled(" ".to_string(), style.clone());
                }
                _ => {}
            }
        }
    }

    /// Renders inline content with the default text style.
    ///
    /// This is a convenience method that wraps render_inline_content_with_style,
    /// using the default text style configuration. It applies the configured font size
    /// to the content before rendering.
    fn render_inline_content(&self, para: &mut genpdfi::elements::Paragraph, tokens: &[Token]) {
        let style = genpdfi::style::Style::new().with_font_size(self.style.text.size);
        self.render_inline_content_with_style(para, tokens, style);
    }

    /// Renders a blockquote, splitting body tokens into "lines" on Newline
    /// boundaries so a multi-line `> a\n> b\n> c` quote renders as three
    /// visible lines. Block-level tokens that ended up inside the body
    /// (Heading after Fix H, Code after Fix I) are recursed into the
    /// matching renderer with the `> ` prefix on a separate line above.
    fn render_blockquote(&self, doc: &mut Document, body: &[Token]) {
        let bq = &self.style.block_quote;
        doc.push(genpdfi::elements::Break::new(bq.before_spacing));

        let mut style = genpdfi::style::Style::new().with_font_size(bq.size);
        if bq.italic {
            style = style.italic();
        }
        if bq.bold {
            style = style.bold();
        }
        if let Some(color) = bq.text_color {
            style = style.with_color(genpdfi::style::Color::Rgb(color.0, color.1, color.2));
        }

        // Group body tokens by Newline boundaries; emit one paragraph per
        // group with a "> " prefix. Block-level tokens (Heading, Code,
        // ListItem, HorizontalRule) inside the body break the current group
        // and route to their dedicated renderer.
        let mut buffer: Vec<Token> = Vec::new();
        let flush_inline = |this: &Pdf,
                            doc: &mut Document,
                            buffer: &mut Vec<Token>,
                            style: &genpdfi::style::Style| {
            if buffer.is_empty() {
                return;
            }
            let mut para = genpdfi::elements::Paragraph::default();
            para.push_styled("> ".to_string(), style.clone());
            this.render_inline_content_with_style(&mut para, buffer, style.clone());
            doc.push(para);
            buffer.clear();
        };

        for token in body {
            match token {
                Token::Newline => {
                    flush_inline(self, doc, &mut buffer, &style);
                }
                Token::Heading(content, level) => {
                    flush_inline(self, doc, &mut buffer, &style);
                    self.render_heading(doc, content, *level);
                }
                Token::Code(lang, content) if content.contains('\n') => {
                    flush_inline(self, doc, &mut buffer, &style);
                    self.render_code_block(doc, lang, content);
                }
                Token::HorizontalRule => {
                    flush_inline(self, doc, &mut buffer, &style);
                    doc.push(genpdfi::elements::Break::new(
                        self.style.horizontal_rule.after_spacing,
                    ));
                }
                Token::ListItem {
                    content,
                    ordered,
                    number,
                    checked,
                } => {
                    flush_inline(self, doc, &mut buffer, &style);
                    self.render_list_item(doc, content, *ordered, *number, *checked, 0);
                }
                _ => buffer.push(token.clone()),
            }
        }
        flush_inline(self, doc, &mut buffer, &style);

        doc.push(genpdfi::elements::Break::new(bq.after_spacing));
    }

    /// Renders a code block with appropriate styling.
    ///
    /// This method handles multi-line code blocks, rendering each line as a separate
    /// paragraph with the configured code style. It applies the code font size and
    /// text color settings, and adds the configured spacing after the block.
    fn render_code_block(&self, doc: &mut Document, _lang: &str, content: &str) {
        doc.push(genpdfi::elements::Break::new(
            self.style.code.before_spacing,
        ));

        let mut style = genpdfi::style::Style::new().with_font_size(self.style.code.size);
        if let Some(color) = self.style.code.text_color {
            style = style.with_color(genpdfi::style::Color::Rgb(color.0, color.1, color.2));
        }

        let indent = "    "; // TODO: make this configurable from style match.
        for line in content.split('\n') {
            let mut para = genpdfi::elements::Paragraph::default();
            para.push_styled(format!("{}{}", indent, line), style.clone());
            doc.push(para);
        }
        doc.push(genpdfi::elements::Break::new(self.style.code.after_spacing));
    }

    /// Renders a list item with appropriate styling and formatting.
    ///
    /// This method handles both ordered and unordered list items, with support for nested lists.
    /// For ordered lists, it includes the item number prefixed with a period (like "1."), while
    /// unordered lists use a bullet point dash character. The content is rendered with the
    /// configured list item style settings from the document style configuration.
    ///
    /// The method processes both the direct content of the list item as well as any nested list
    /// items recursively. Each nested level increases the indentation by 4 spaces to create a
    /// visual hierarchy. The method filters the content to separate inline elements from nested
    /// list items, rendering the inline content first before processing any nested items.
    ///
    /// After rendering each list item's content, appropriate spacing is added based on the
    /// configured after_spacing value. The method maintains consistent styling throughout the
    /// list hierarchy while allowing for proper nesting and indentation of complex list structures.
    fn render_list_item(
        &self,
        doc: &mut Document,
        content: &[Token],
        ordered: bool,
        number: Option<usize>,
        checked: Option<bool>,
        nesting_level: usize,
    ) {
        doc.push(genpdfi::elements::Break::new(
            self.style.list_item.before_spacing,
        ));
        let mut para = genpdfi::elements::Paragraph::default();
        let style = genpdfi::style::Style::new().with_font_size(self.style.list_item.size);

        let indent = "    ".repeat(nesting_level);
        let marker_prefix = if !ordered {
            format!("{}- ", indent)
        } else if let Some(n) = number {
            format!("{}{}. ", indent, n)
        } else {
            indent.clone()
        };
        let bullet = match checked {
            Some(true) => format!("{}[x] ", marker_prefix),
            Some(false) => format!("{}[ ] ", marker_prefix),
            None => marker_prefix,
        };
        para.push_styled(bullet, style.clone());

        let inline_content: Vec<Token> = content
            .iter()
            .filter(|token| !matches!(token, Token::ListItem { .. }))
            .cloned()
            .collect();
        self.render_inline_content_with_style(&mut para, &inline_content, style);
        doc.push(para);
        doc.push(genpdfi::elements::Break::new(
            self.style.list_item.after_spacing,
        ));

        for token in content {
            if let Token::ListItem {
                content: nested_content,
                ordered: nested_ordered,
                number: nested_number,
                checked: nested_checked,
            } = token
            {
                self.render_list_item(
                    doc,
                    nested_content,
                    *nested_ordered,
                    *nested_number,
                    *nested_checked,
                    nesting_level + 1,
                );
            }
        }
    }

    /// Renders a table with headers, alignment information, and rows.
    ///
    /// Each row is a vector of cells.
    ///
    /// The table is rendered using genpdfi's TableLayout with proper column weights
    /// and cell borders. Each cell content is processed as inline tokens to handle
    /// formatting within table them.
    fn render_table(
        &self,
        doc: &mut Document,
        headers: &Vec<Vec<Token>>,
        aligns: &Vec<Alignment>,
        rows: &Vec<Vec<Vec<Token>>>,
    ) {
        doc.push(genpdfi::elements::Break::new(
            self.style.text.before_spacing,
        ));

        let column_count = headers.len();
        let column_weights = vec![1; column_count];

        let mut table = genpdfi::elements::TableLayout::new(column_weights);
        table.set_cell_decorator(genpdfi::elements::FrameCellDecorator::new(
            true, true, false,
        ));

        // Render header row
        let mut header_row = table.row();
        for (i, header_cell) in headers.iter().enumerate() {
            let mut para = genpdfi::elements::Paragraph::default();
            let style = genpdfi::style::Style::new().with_font_size(self.style.table_header.size);

            if let Some(align) = aligns.get(i) {
                para.set_alignment(*align);
            }

            self.render_inline_content_with_style(&mut para, header_cell, style);
            header_row.push_element(para);
        }

        if let Err(_) = header_row.push() {
            warn!("Failed rendering a table");
            return; // Skip the entire table if header fails
        }

        // Render data rows
        for (row_idx, row) in rows.iter().enumerate() {
            let mut table_row = table.row();

            for (i, cell_tokens) in row.iter().enumerate() {
                let mut para = genpdfi::elements::Paragraph::default();
                let style = genpdfi::style::Style::new().with_font_size(self.style.table_cell.size);

                if let Some(align) = aligns.get(i) {
                    para.set_alignment(*align);
                }

                self.render_inline_content_with_style(&mut para, cell_tokens, style);
                table_row.push_element(para);
            }

            if let Err(_) = table_row.push() {
                warn!("Failed to push row {} in a table", row_idx);
                continue; // Continue with next row
            }
        }

        doc.push(table);
        doc.push(genpdfi::elements::Break::new(self.style.text.after_spacing));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::styling::StyleMatch;

    // Helper function to create a basic PDF instance for testing
    fn create_test_pdf(tokens: Vec<Token>) -> Pdf {
        Pdf::new(tokens, StyleMatch::default(), None).expect("Failed to create test PDF")
    }

    #[test]
    fn test_pdf_creation() {
        let pdf = create_test_pdf(vec![]);
        assert!(pdf.input.is_empty());

        // Test that both font families exist
        let _font_family = &pdf.font_family;
        let _code_font_family = &pdf.code_font_family;

        // Since FontData's fields are private and it doesn't implement comparison traits,
        // we can only verify that the PDF was created successfully with these fonts
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_heading() {
        let tokens = vec![
            Token::Heading(vec![Token::Text("Test Heading".to_string())], 1),
            Token::Heading(vec![Token::Text("Subheading".to_string())], 2),
            Token::Heading(vec![Token::Text("Sub-subheading".to_string())], 3),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        // Document should be created successfully
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_paragraphs() {
        let tokens = vec![
            Token::Text("First paragraph".to_string()),
            Token::Newline,
            Token::Text("Second paragraph".to_string()),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_list_items() {
        let tokens = vec![
            Token::ListItem {
                content: vec![Token::Text("First item".to_string())],
                ordered: false,
                number: None,
                checked: None,
            },
            Token::ListItem {
                content: vec![Token::Text("Second item".to_string())],
                ordered: true,
                number: Some(1),
                checked: None,
            },
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_nested_list_items() {
        let tokens = vec![Token::ListItem {
            content: vec![
                Token::Text("Parent item".to_string()),
                Token::ListItem {
                    content: vec![Token::Text("Child item".to_string())],
                    ordered: false,
                    number: None,
                    checked: None,
                },
            ],
            ordered: false,
            number: None,
            checked: None,
        }];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_code_blocks() {
        let tokens = vec![Token::Code(
            "rust".to_string(),
            "fn main() {\n    println!(\"Hello\");\n}".to_string(),
        )];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_inline_formatting() {
        let tokens = vec![
            Token::Text("Normal ".to_string()),
            Token::Emphasis {
                level: 1,
                content: vec![Token::Text("italic".to_string())],
            },
            Token::Text(" and ".to_string()),
            Token::StrongEmphasis(vec![Token::Text("bold".to_string())]),
            Token::Text(" text".to_string()),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_links() {
        let tokens = vec![
            Token::Text("Here is a ".to_string()),
            Token::Link("link".to_string(), "https://example.com".to_string()),
            Token::Text(" to click".to_string()),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_horizontal_rule() {
        let tokens = vec![
            Token::Text("Before rule".to_string()),
            Token::HorizontalRule,
            Token::Text("After rule".to_string()),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_mixed_content() {
        let tokens = vec![
            Token::Heading(vec![Token::Text("Title".to_string())], 1),
            Token::Text("Some text ".to_string()),
            Token::Link("with link".to_string(), "https://example.com".to_string()),
            Token::Newline,
            Token::ListItem {
                content: vec![Token::Text("List item".to_string())],
                ordered: false,
                number: None,
                checked: None,
            },
            Token::Code("rust".to_string(), "let x = 42;".to_string()),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_empty_content() {
        let pdf = create_test_pdf(vec![]);
        let doc = pdf.render_into_document();
        assert!(Pdf::render(doc, "/dev/null").is_none());
    }

    #[test]
    fn test_render_invalid_path() {
        let pdf = create_test_pdf(vec![Token::Text("Test".to_string())]);
        let doc = pdf.render_into_document();
        let result = Pdf::render(doc, "/nonexistent/path/file.pdf");
        assert!(result.is_some()); // Should return an error message
    }

    #[test]
    fn test_render_to_bytes() {
        let tokens = vec![
            Token::Heading(vec![Token::Text("Test Document".to_string())], 1),
            Token::Text("This is a test paragraph.".to_string()),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        let result = Pdf::render_to_bytes(doc);

        assert!(result.is_ok());
        let pdf_bytes = result.unwrap();
        assert!(!pdf_bytes.is_empty());
        // PDF files should start with "%PDF-"
        assert!(pdf_bytes.starts_with(b"%PDF-"));
    }

    #[test]
    fn test_render_to_bytes_empty_document() {
        let pdf = create_test_pdf(vec![]);
        let doc = pdf.render_into_document();
        let result = Pdf::render_to_bytes(doc);

        assert!(result.is_ok());
        let pdf_bytes = result.unwrap();
        assert!(!pdf_bytes.is_empty());
        assert!(pdf_bytes.starts_with(b"%PDF-"));
    }

    #[test]
    fn test_render_to_bytes_complex_content() {
        let tokens = vec![
            Token::Heading(vec![Token::Text("Main Title".to_string())], 1),
            Token::Text("Introduction paragraph.".to_string()),
            Token::Heading(vec![Token::Text("Section 1".to_string())], 2),
            Token::ListItem {
                content: vec![Token::Text("First item".to_string())],
                ordered: false,
                number: None,
                checked: None,
            },
            Token::ListItem {
                content: vec![Token::Text("Second item".to_string())],
                ordered: false,
                number: None,
                checked: None,
            },
            Token::Code(
                "rust".to_string(),
                "fn main() {\n    println!(\"Hello\");\n}".to_string(),
            ),
            Token::Link(
                "Example Link".to_string(),
                "https://example.com".to_string(),
            ),
        ];
        let pdf = create_test_pdf(tokens);
        let doc = pdf.render_into_document();
        let result = Pdf::render_to_bytes(doc);

        assert!(result.is_ok());
        let pdf_bytes = result.unwrap();
        assert!(!pdf_bytes.is_empty());
        assert!(pdf_bytes.starts_with(b"%PDF-"));
    }
}