vex2pdf 4.0.0

A tool to convert CycloneDX(VEX) JSON or XML documents to PDF reports
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
//! PDF generation functionality for CycloneDX (VEX) reports.
//!
//! This module handles the conversion from CycloneDX (VEX) data structures to
//! formatted PDF documents using the genpdf library.
//!
//! The generator supports various VEX elements, including vulnerabilities,
//! components, and document metadata.
//!

use crate::lib_utils::config::Config;
use crate::pdf::font_config::FontsDir;
use cyclonedx_bom::models::tool::Tools;
use cyclonedx_bom::models::vulnerability_analysis::{ImpactAnalysisResponse, ImpactAnalysisState};
use cyclonedx_bom::prelude::Bom;
use genpdf::elements::Paragraph;
use genpdf::style::{Color, Style, StyledString};
use genpdf::{Alignment, Document, Element};
use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::sync::Arc;

// begin macro utilities
macro_rules! create_versioned_comp_styled {
    ($comp_name:expr,$version_option:expr,$comp_style:expr,$version_style:expr) => {{
        let mut meta_tool_para =
            Paragraph::default().styled_string($comp_name.to_string(), $comp_style);

        if let Some(tool_ver) = &$version_option {
            let tool_ver_str = StyledString::new(format!(" ({tool_ver})"), $version_style);
            meta_tool_para.push(tool_ver_str);
        }
        meta_tool_para
    }};
}
// end macro utilities
/// Utilities used by the generator
pub(super) struct Utils;
impl Utils {
    /// This is used for analysis results to prettify labels like 'not_justified' into "Not Justified"
    /// as an example. This applies to everything containing an underscore in it
    pub(super) fn prettify_string_analysis(state_str: &str) -> String {
        let ret: Vec<String> = state_str
            .split('_')
            .map(|e| {
                if !e.is_empty() {
                    format!("{}{}", &e[0..1].to_uppercase(), &e[1..])
                } else {
                    String::new()
                }
            })
            .collect();

        ret.join(" ").to_string()
    }

    /// Returns a styled format for impact analysis response actions.
    ///
    /// Color scheme:
    /// - Update/Rollback: Blue (action available)
    /// - Workaround: Orange (temporary solution)
    /// - Can't/Won't Fix: Red (no fix)
    pub(super) fn get_style_analysis_response(response: &ImpactAnalysisResponse) -> Style {
        match response {
            ImpactAnalysisResponse::Update => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(0, 102, 204)) // Blue - action available
            }
            ImpactAnalysisResponse::Rollback => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(0, 102, 204)) // Blue - action available
            }
            ImpactAnalysisResponse::WorkaroundAvailable => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(255, 140, 0)) // Orange - temporary solution
            }
            ImpactAnalysisResponse::CanNotFix => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(178, 34, 34)) // Red - no fix possible
            }
            ImpactAnalysisResponse::WillNotFix => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(178, 34, 34)) // Red - no fix planned
            }
            ImpactAnalysisResponse::UndefinedResponse(_) => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(128, 128, 128)) // Gray - undefined
            }
        }
    }

    pub(super) fn get_style_analysis_state(state: &ImpactAnalysisState) -> Style {
        match state {
            ImpactAnalysisState::Resolved => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(0, 128, 0)) // Green - safe/resolved
                    .bold()
            }
            ImpactAnalysisState::ResolvedWithPedigree => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(0, 100, 0)) // Dark green - verified safe
                    .bold()
            }
            ImpactAnalysisState::Exploitable => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(178, 34, 34)) // Firebrick red - critical attention
                    .bold()
            }
            ImpactAnalysisState::InTriage => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(255, 140, 0)) // Dark orange - warning/investigation
                    .bold()
            }
            ImpactAnalysisState::FalsePositive => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(70, 130, 180)) // Steel blue - informational
                    .bold()
            }
            ImpactAnalysisState::NotAffected => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(34, 139, 34)) // Forest green - safe/not applicable
                    .bold()
            }
            ImpactAnalysisState::UndefinedImpactAnalysisState(_) => {
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(128, 128, 128)) // Gray - undefined/unknown
                    .bold()
            }
        }
    }

    /// returns a formatted text in the form > **key**: value < where value can be a long text
    /// also converts any newline character in val to real newlines for proper rendering
    pub(super) fn get_formatted_key_val_text(key: &str, val: &str, style: Style) -> Paragraph {
        let mut lines = val.split('\n');
        let first_line = lines.next().unwrap_or_default().trim(); // it is safe to unwrap here as we mapped the reference to return None when empty thus moving into the else branch and not here
        let mut res = Paragraph::default()
            .styled_string(format!("{key}: "), style.bold())
            .styled_string(first_line, style);

        for line in lines {
            res.push_styled(line, style);
        }

        res
    }

    /// Formats a vector of styled strings as a bracketed, comma-separated paragraph.
    ///
    /// Creates a paragraph in the format `[ item1, item2, item3 ]` where each item
    /// retains its individual styling while brackets and commas use the provided style.
    ///
    /// # Arguments
    /// * `multi_style_scentence` - Vector of `StyledString` items to format
    /// * `style` - Style for brackets `[ ]` and comma separators `, `
    ///
    /// # Returns
    /// A [`Paragraph`] with the formatted content. Returns a paragraph object representing `[ ]` if the vector is empty.
    ///
    pub(super) fn get_styled_vector_as_paragraph(
        key: Option<impl ToString>,
        multi_style_scentence: Vec<StyledString>,
        style: Style,
    ) -> Paragraph {
        let mut scentence_iter = multi_style_scentence.into_iter();

        let mut styled_vector_par = Paragraph::default();
        if let Some(key_val) = key {
            styled_vector_par.push_styled(format!("{}: ", key_val.to_string()), style.bold());
        }

        styled_vector_par.push_styled("[ ", style.bold());

        styled_vector_par.push(scentence_iter.next().unwrap_or_default());

        for scentence_part in scentence_iter {
            styled_vector_par.push_styled(", ", style);
            styled_vector_par.push(scentence_part);
        }

        styled_vector_par.push_styled(" ]", style.bold());

        styled_vector_par
    }
}

/// ComponentTuple is a type that should hold a reference to component_name and component_version respectively
type ComponentTuple<'b> = (&'b str, &'b str);
pub struct PdfGenerator {
    title_style: Style,
    header_style: Style,
    normal_style: Style,
    indent_style: Style,
    comp_name_style: Style,
    version_style: Style,
    cve_id_style: Style,
    cve_published_style: Style,
    /// This is the full configuration passed to the generator, including the `show_components`, `show_novulns_msg` and more
    /// this replaces the old behaviour of individually listing the properties as members of this struct
    /// this is an Arc for cases where the pdfgenerator is used by multiple threads to avoid copying
    /// around the entire configuration on every thread's stack
    config: Arc<Config>,
}

impl Default for PdfGenerator {
    /// Creates a new PDF generator with default report and PDF titles.
    ///
    /// This implementation of the `Default` trait provides a convenient way to create a
    /// `PdfGenerator` with standard titles suitable for vulnerability reports.
    ///
    /// # Returns
    ///
    /// A new `PdfGenerator` instance with:
    /// - Report title: "Vulnerability Report Document"
    /// - PDF title: "VEX Vulnerability Report"
    /// - Default styling for all text elements
    ///
    /// # Examples
    ///
    /// ```rust
    /// use vex2pdf::pdf::generator::PdfGenerator;
    /// use std::default::Default;
    ///
    /// // Create a generator with default settings
    /// let generator = PdfGenerator::default();
    ///
    /// // Alternatively
    /// let generator: PdfGenerator = Default::default();
    /// ```
    fn default() -> Self {
        Self::new(Arc::new(Config::default()))
    }
}

impl<'b> PdfGenerator {
    ///
    /// # Arguments
    ///
    /// * `report_title` - The title displayed as the main heading on the first page of the report
    /// * `pdf_title` - The title displayed in the PDF reader window/tab when the document is opened
    /// * `show_novulns_msg` - Whether the `No Vulnerabilities reported` message is shown when no vulnerabilities are available
    /// * `show_components` - Whether the `components section` is shown
    ///
    /// # Returns
    ///
    /// A new `PdfGenerator` instance with default styles and the specified titles
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use vex2pdf::lib_utils::config::Config;
    /// use vex2pdf::pdf::generator::PdfGenerator;
    ///
    /// //  *Warning* : While this is a valid use of the software config Default implementation
    /// //  it should be noted that default reads environment settings like the working directory and
    /// //  thus may not fit your needs.
    ///
    /// //  Create a generator with custom titles showing a No Vulnerabilities message if
    /// // the vulnerabilities array is empty and hiding the components sections
    /// let config = Config {
    ///     show_novulns_msg: true,
    ///     show_components: false,
    ///     report_title: Some(String::from("Custom title")),
    ///     pdf_meta_name: Some(String::from("Custom meta name")),
    ///     ..Config::default()
    /// };
    /// let generator = PdfGenerator::new(Arc::new(config));
    /// ```
    pub fn new(config: Arc<Config>) -> Self {
        // Initialize with default styles
        let title_style = Style::new()
            .with_font_size(18)
            .with_color(Color::Rgb(0, 0, 80));

        let header_style = Style::new()
            .with_font_size(14)
            .with_color(Color::Rgb(0, 0, 80));

        let normal_style = Style::new().with_font_size(11);

        let indent_style = Style::new()
            .with_font_size(10)
            .with_color(Color::Rgb(40, 40, 40));

        let comp_name_style = Style::new()
            .with_font_size(10)
            .with_color(Color::Rgb(0, 51, 102))
            .italic();

        let version_style = Style::new()
            .with_font_size(10)
            .with_color(Color::Rgb(128, 128, 128));
        let cve_published_style = version_style.with_font_size(6).italic();

        let cve_id_style = Style::new()
            .with_font_size(11)
            .with_color(Color::Rgb(139, 0, 0))
            .bold();
        Self {
            title_style,
            header_style,
            normal_style,
            indent_style,
            comp_name_style,
            version_style,
            cve_id_style,
            cve_published_style,
            config,
        }
    }

    /// Gets the default title for the pdf metadata
    fn get_default_pdf_meta_name() -> &'static str {
        "Vulnerability Report"
    }

    /// Gets the default title for pure BoM reports with no vulnerabilities' section
    fn get_default_pdf_meta_name_bom() -> &'static str {
        "Bill of Materials"
    }

    /// Gets the default title of the report which shows on the first page
    fn get_default_report_title() -> &'static str {
        "Vulnerability Report Document"
    }

    /// Gets the default title of the report which shows on the first page for pure BoM reports
    /// with no vulnerabilies' section
    fn get_default_report_title_bom() -> &'static str {
        "Bill of Materials Document"
    }

    /// Generates a PDF report from a CycloneDX VEX document.
    ///
    /// # Arguments
    ///
    /// * `vex` - The CycloneDX VEX document to convert
    /// * `output_path` - Path where the PDF report will be saved
    ///
    /// # Returns
    ///
    /// Result indicating success or an error with details
    pub fn generate_pdf<P: AsRef<Path>>(
        &self,
        vex: &'b Bom,
        output_path: P,
    ) -> Result<(), io::Error> {
        // Extract component list if available this will later be used to extract affected components

        let mut comp_ref_map = HashMap::<&'b str, ComponentTuple>::new();

        if let Some(components) = &vex.components {
            // preallocate our primary container
            comp_ref_map = HashMap::with_capacity(components.0.len());

            for component in &components.0 {
                // extract component name and version
                let component_version = if let Some(version) = &component.version {
                    version
                } else {
                    "undefined"
                };
                let component_detail: ComponentTuple = (&component.name, component_version);

                if let Some(ref_id) = &component.bom_ref {
                    comp_ref_map.insert(ref_id, component_detail);
                }
            }
        }
        let mut doc = Document::new(FontsDir::build().font_family);
        // Set up the document with default fonts

        let document_title = self.get_report_title();
        let pdf_title = self.get_doc_meta_name();

        doc.set_title(pdf_title);
        let mut decorator = genpdf::SimplePageDecorator::new();
        decorator.set_margins(10);
        let header_title = document_title.to_string();
        decorator.set_header(move |page| {
            let mut layout = genpdf::elements::LinearLayout::vertical();
            if page > 1 {
                layout.push(Paragraph::new(&header_title).aligned(Alignment::Left));

                layout.push(Paragraph::new(format!("Page {page}")).aligned(Alignment::Center));
                layout.push(genpdf::elements::Break::new(2));
            }
            layout.styled(
                Style::new()
                    .with_font_size(10)
                    .with_color(Color::Rgb(0, 0, 80)),
            )
        });

        doc.set_page_decorator(decorator);

        // Add title and basic information
        doc.push(Paragraph::default().styled_string(document_title, self.title_style));
        doc.push(genpdf::elements::Break::new(1.0));

        // Add metadata if available
        if let Some(metadata) = &vex.metadata {
            doc.push(Paragraph::default().styled_string("Document Information", self.header_style));
            doc.push(genpdf::elements::Break::new(1));

            // Add timestamp if available
            if let Some(timestamp) = &metadata.timestamp {
                doc.push(
                    Paragraph::default()
                        .styled_string(format!("Date: {timestamp}"), self.normal_style.italic()),
                );
            }

            doc.push(genpdf::elements::Break::new(1));

            // Add tools information if available
            if let Some(tools) = &metadata.tools {
                doc.push(Paragraph::default().styled_string("Tools:", self.normal_style.bold()));

                let mut ul_tools = genpdf::elements::UnorderedList::new();

                match tools {
                    Tools::List(tools_list) => {
                        for tool in tools_list {
                            if let Some(tool_name) = &tool.name {
                                let meta_tool_para = create_versioned_comp_styled!(
                                    tool_name,
                                    &tool.version,
                                    self.indent_style,
                                    self.version_style
                                );
                                ul_tools.push(meta_tool_para);
                            }
                        }
                    }
                    Tools::Object {
                        services: services_obj,
                        components: components_obj,
                    } => {
                        // Handle components used as tools
                        if let Some(components) = &components_obj {
                            for component in &components.0 {
                                let styled_comp = create_versioned_comp_styled!(
                                    &component.name,
                                    &component.version,
                                    self.indent_style,
                                    self.version_style
                                );
                                ul_tools.push(styled_comp);
                            }
                        }

                        // Handle services used as tools
                        if let Some(services) = &services_obj {
                            for service in &services.0 {
                                let styled_service = create_versioned_comp_styled!(
                                    &service.name,
                                    &service.version,
                                    self.indent_style,
                                    self.version_style
                                );
                                ul_tools.push(styled_service);
                            }
                        }
                    }
                }

                doc.push(ul_tools);
                doc.push(genpdf::elements::Break::new(1));
            }

            if let Some(component) = &metadata.component {
                let mut comp_para = Paragraph::default()
                    .styled_string("Component name : ", self.normal_style.bold())
                    .styled_string(component.name.to_string(), self.indent_style);

                if let Some(comp_vers) = &component.version {
                    let ver_str = StyledString::new(format!(" ({comp_vers})"), self.version_style);
                    comp_para.push(ver_str);
                }

                doc.push(comp_para);
            }

            doc.push(genpdf::elements::Break::new(1.0));
        }

        // Add basic BOM information
        doc.push(
            Paragraph::default()
                .styled_string("BOM Format: ", self.normal_style.bold())
                .styled_string("CycloneDX", self.normal_style),
        );
        doc.push(
            Paragraph::default()
                .styled_string("Specification Version: ", self.normal_style.bold())
                .styled_string(format!("{}", vex.spec_version), self.normal_style),
        );

        doc.push(
            Paragraph::default()
                .styled_string("Version: ", self.normal_style.bold())
                .styled_string(format!("{}", vex.version), self.normal_style),
        );

        if let Some(serial) = &vex.serial_number {
            doc.push(
                Paragraph::default()
                    .styled_string("Serial Number: ", self.normal_style.bold())
                    .styled_string(format!("{serial}"), self.normal_style),
            );
        }

        doc.push(genpdf::elements::Break::new(2.0));

        // Add a Vulnerabilities section or a components list or both depending on user options

        if !self.config.pure_bom_novulns {
            doc = self.render_vulns(doc, vex, &comp_ref_map);
        }

        if self.config.pure_bom_novulns || self.config.show_components {
            doc = self.render_components(doc, vex);
        }

        // Render the document
        doc.render_to_file(output_path)
            .expect("failed to write file");

        Ok(())
    }

    /// report title helper
    fn get_report_title(&self) -> &str {
        if let Some(title) = self.config.report_title.as_ref() {
            title
        } else if self.config.pure_bom_novulns {
            Self::get_default_report_title_bom()
        } else {
            Self::get_default_report_title()
        }
    }

    /// Document meta name helper
    fn get_doc_meta_name(&self) -> &str {
        if let Some(meta_name) = self.config.pdf_meta_name.as_ref() {
            meta_name
        } else if self.config.pure_bom_novulns {
            Self::get_default_pdf_meta_name_bom()
        } else {
            Self::get_default_pdf_meta_name()
        }
    }
    /// Internal helper function specific for the Vulnerabilities section
    fn render_vulns(
        &self,
        mut doc: Document,
        vex: &Bom,
        comp_ref_map: &HashMap<&'b str, ComponentTuple>,
    ) -> Document {
        // First determine if vulnerabilities exist
        let mut vulns_available = false;
        if let Some(vulnerabilities) = &vex.vulnerabilities {
            vulns_available = !vulnerabilities.0.is_empty();
        }

        // Decide if we should show the vulnerabilities section at all
        let show_vulns_section = vulns_available || self.config.show_novulns_msg;

        if show_vulns_section {
            doc.push(Paragraph::default().styled_string("Vulnerabilities", self.header_style));
            doc.push(genpdf::elements::Break::new(1.0));
        }

        if let Some(vulnerabilities) = &vex.vulnerabilities {
            let mut vulns_ordered_list = genpdf::elements::OrderedList::new();

            // Add each vulnerability
            for vuln in &vulnerabilities.0 {
                let mut vuln_layout = genpdf::elements::LinearLayout::vertical();

                let published_date = vuln
                    .published
                    .as_ref()
                    .map(|e| format!(" -- Published: {}", e));
                let id_paragraph = if let Some(vuln_id) = &vuln.id {
                    // do we have a published date if yes append it to the cve
                    let mut para = Paragraph::default()
                        .styled_string("ID: ", self.normal_style)
                        .styled_string(format!("{vuln_id} "), self.cve_id_style);

                    if let Some(date) = published_date {
                        para.push_styled(date, self.cve_published_style);
                    }

                    para
                } else {
                    Paragraph::default().styled_string("ID: N/A", self.normal_style)
                };

                vuln_layout.push(id_paragraph);
                macro_rules! add_named_para {
    ($name:expr,$content:ident,$b_show_if_empty:expr) => {

                let content_unpacked_ref =
                    $content.as_ref().filter(|e| !e.is_empty());
                let name = format!("{}: ",$name);

                if let Some(desc) = content_unpacked_ref {
                    // we need to split around \n new line characters if they exist else they will be rendered as gibberish
                    let mut lines = desc.split('\n');
                    let first_line = lines.next().unwrap_or_default().trim(); // it is safe to unwrap here as we mapped the reference to return None when empty thus moving into the else branch and not here
                    vuln_layout.push(
                        Paragraph::default()
                            .styled_string(name, self.indent_style.bold())
                            .styled_string(first_line, self.indent_style),
                    );

                    for line in lines {
                        vuln_layout.push(
                            Paragraph::default().styled_string(line.trim(), self.indent_style),
                        )
                    }
                } else if $b_show_if_empty {
                    vuln_layout.push(
                        Paragraph::default()
                            .styled_string(name, self.indent_style.bold())
                            .styled_string("N/A", self.indent_style),
                    );
                };
    };
}
                let desc_ref = vuln.description.as_ref();
                add_named_para!("Description", desc_ref, true);
                // add recommendation
                let rec_ref = vuln.recommendation.as_ref();
                if rec_ref.is_some() {
                    vuln_layout.push(genpdf::elements::Break::new(0.25))
                };
                add_named_para!("Recommendation", rec_ref, false);

                // Line break after the CVE entry section
                vuln_layout.push(genpdf::elements::Break::new(0.5));

                let mut ratings_list = genpdf::elements::UnorderedList::new();

                if let Some(ratings) = &vuln.vulnerability_ratings {
                    for rating in &ratings.0 {
                        let rating_method = if let Some(method) = &rating.score_method {
                            method.to_string()
                        } else {
                            "N/A".to_string()
                        };

                        let source_str: Option<String> =
                            rating.vulnerability_source.as_ref().and_then(|source| {
                                source
                                    .name
                                    .as_ref()
                                    .map(|source_name| source_name.to_string())
                            });

                        if let Some(severity) = &rating.severity {
                            // add Severity ratings and sources

                            let mut severity_par = Paragraph::default()
                                .styled_string("Severity: ", self.indent_style.bold())
                                .styled_string(
                                    format!("{severity} ({rating_method}"),
                                    self.indent_style,
                                );

                            if let Some(source_name) = source_str {
                                severity_par = severity_par
                                    .styled_string(" — Source: ", self.indent_style)
                                    .styled_string(source_name, self.indent_style);
                            }

                            severity_par = severity_par.styled_string(")", self.indent_style);
                            ratings_list.push(severity_par);
                        }
                    }
                }

                // add our ratings list to the vuln layout
                vuln_layout.push(ratings_list);

                // add analysis results if they exist
                if let Some(analysis) = &vuln.vulnerability_analysis {
                    // no point showing the analysis if we have no state
                    if let Some(analysis_state) = &analysis.state {
                        let mut analysis_para_layout = genpdf::elements::LinearLayout::vertical();

                        analysis_para_layout.push(
                            Paragraph::default()
                                .styled_string("Analysis: ", self.indent_style.bold())
                                .styled_string(
                                    Utils::prettify_string_analysis(
                                        analysis_state.to_string().as_str(),
                                    ),
                                    Utils::get_style_analysis_state(analysis_state),
                                ),
                        );

                        // indented bullet points for analysis data
                        let mut analysis_details_ul = genpdf::elements::UnorderedList::new();

                        // handle responses if they exist
                        if let Some(responses) = &analysis.responses {
                            let mut responses_scentence =
                                Vec::<StyledString>::with_capacity(responses.len());

                            for response in responses {
                                responses_scentence.push(StyledString::new(
                                    Utils::prettify_string_analysis(response.to_string().as_str()),
                                    Utils::get_style_analysis_response(response),
                                ));
                            }

                            let responses_par = Utils::get_styled_vector_as_paragraph(
                                Some("Responses"),
                                responses_scentence,
                                self.indent_style,
                            );

                            analysis_details_ul.push(responses_par);
                        }

                        // handle justification if it exists
                        if let Some(justification) = &analysis.justification {
                            let justif_par = Utils::get_formatted_key_val_text(
                                "Justification",
                                &Utils::prettify_string_analysis(
                                    justification.to_string().as_str(),
                                ),
                                self.indent_style,
                            );

                            analysis_details_ul.push(justif_par)
                        }

                        // Show details if they exist
                        if let Some(details) = &analysis.detail {
                            analysis_details_ul.push(Utils::get_formatted_key_val_text(
                                "Details",
                                details,
                                self.indent_style,
                            ));
                        }

                        // add the finalized analysis section

                        analysis_para_layout.push(analysis_details_ul);

                        vuln_layout.push(genpdf::elements::Break::new(0.5));
                        vuln_layout.push(analysis_para_layout);
                    }
                }

                // add affected components to vulnerability
                if !comp_ref_map.is_empty() {
                    // get list of affected references
                    if let Some(affected_comps) = &vuln.vulnerability_targets {
                        let mut affected_comps_detailed: Vec<&ComponentTuple> =
                            Vec::with_capacity(affected_comps.0.len());

                        for comp in &affected_comps.0 {
                            if let Some(map_val) = comp_ref_map.get(comp.bom_ref.as_str()) {
                                affected_comps_detailed.push(map_val);
                            }
                        }

                        // Create our affected components paragraph
                        let mut affected_comp_para = Paragraph::default().styled_string(
                            "Affected Document Components : [ ",
                            self.indent_style.bold(),
                        );

                        for (i, affected_comp) in affected_comps_detailed.iter().enumerate() {
                            if i > 0 {
                                affected_comp_para.push(", ");
                            }

                            affected_comp_para.push_styled(affected_comp.0, self.comp_name_style);
                            affected_comp_para
                                .push_styled(format!(": {}", affected_comp.1), self.version_style);
                        }
                        affected_comp_para.push_styled(" ]", self.indent_style.bold());

                        // add our affected components to the vulnerability layout
                        vuln_layout.push(genpdf::elements::Break::new(0.5));
                        vuln_layout.push(affected_comp_para);
                    }
                }

                vuln_layout.push(genpdf::elements::Break::new(1));
                // Add vulnerability to numbered list of vulnerabilities
                vulns_ordered_list.push(vuln_layout);
            }

            // list_layout.push(ordered_list);
            doc.push(vulns_ordered_list);
            doc.push(genpdf::elements::Break::new(0.5));
        }

        //Add message if vulns are not available
        if !vulns_available && self.config.show_novulns_msg {
            let vulns_style = Style::new()
                .bold()
                .with_font_size(16)
                .with_color(Color::Rgb(0, 100, 0));

            doc.push(
                Paragraph::new("No Vulnerabilities reported")
                    .aligned(Alignment::Center)
                    .padded(genpdf::Margins::vh(10, 0))
                    .framed()
                    .styled(vulns_style),
            );
            doc.push(genpdf::elements::Break::new(1.0));
        }

        doc
    }

    fn render_components(&self, mut doc: Document, vex: &Bom) -> Document {
        if let Some(components) = &vex.components {
            doc.push(Paragraph::default().styled_string("Components", self.header_style));
            doc.push(genpdf::elements::Break::new(0.5));

            for component in &components.0 {
                doc.push(
                    Paragraph::default()
                        .styled_string("Name: ", self.indent_style)
                        .styled_string(format!("{}", component.name), self.comp_name_style),
                );

                if let Some(version) = &component.version {
                    doc.push(
                        Paragraph::default()
                            .styled_string("Version: ", self.indent_style)
                            .styled_string(format!("{version}"), self.version_style),
                    );
                }

                doc.push(genpdf::elements::Break::new(0.5));
            }
        }

        doc
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cyclonedx_bom::models::vulnerability_analysis::{
        ImpactAnalysisResponse, ImpactAnalysisState,
    };
    use genpdf::style::{Color, Style, StyledString};

    #[test]
    fn test_prettify_string_analysis() {
        assert_eq!(
            Utils::prettify_string_analysis("not_affected"),
            "Not Affected"
        );
        assert_eq!(
            Utils::prettify_string_analysis("code_not_reachable"),
            "Code Not Reachable"
        );
        assert_eq!(
            Utils::prettify_string_analysis("exploitable"),
            "Exploitable"
        );
        assert_eq!(Utils::prettify_string_analysis(""), "");
    }

    #[test]
    fn test_get_style_analysis_state_exploitable() {
        let state = ImpactAnalysisState::Exploitable;
        let style = Utils::get_style_analysis_state(&state);

        // Verify it returns a style (basic check)
        assert_eq!(style.font_size(), 10);
    }

    #[test]
    fn test_get_style_analysis_state_resolved() {
        let state = ImpactAnalysisState::Resolved;
        let style = Utils::get_style_analysis_state(&state);

        assert_eq!(style.font_size(), 10);
    }

    #[test]
    fn test_get_style_analysis_response_update() {
        let response = ImpactAnalysisResponse::Update;
        let style = Utils::get_style_analysis_response(&response);

        assert_eq!(style.font_size(), 10);
    }

    #[test]
    fn test_get_formatted_key_val_text() {
        let style = Style::new().with_font_size(10);
        let para = Utils::get_formatted_key_val_text("Description", "Test value", style);

        // Basic check that paragraph was created
        assert!(format!("{:?}", para).contains("Description"));
    }

    #[test]
    fn test_get_styled_vector_as_paragraph_with_key() {
        let style = Style::new().with_font_size(10);
        let red_style = Style::new().with_color(Color::Rgb(178, 34, 34));
        let items = vec![
            StyledString::new("Update", red_style),
            StyledString::new("Rollback", red_style),
        ];

        let para = Utils::get_styled_vector_as_paragraph(Some("Response"), items, style);

        // Basic check that paragraph contains expected content
        let debug_str = format!("{:?}", para);
        assert!(debug_str.contains("Response"));
    }

    #[test]
    fn test_get_styled_vector_as_paragraph_without_key() {
        let style = Style::new().with_font_size(10);
        let items = vec![StyledString::new("Item1", style)];

        let para = Utils::get_styled_vector_as_paragraph(None::<String>, items, style);

        // Basic check that paragraph was created
        let debug_str = format!("{:?}", para);
        assert!(debug_str.contains("Item1"));
    }

    #[test]
    fn test_get_styled_vector_as_paragraph_empty() {
        let style = Style::new().with_font_size(10);
        let items: Vec<StyledString> = vec![];

        let para = Utils::get_styled_vector_as_paragraph(Some("Empty"), items, style);

        // Should handle empty vector gracefully
        let debug_str = format!("{:?}", para);
        assert!(debug_str.contains("Empty"));
    }
}