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
use crate::{pdf::Helper, Cell, Error, Row, RowStyle};

use std::iter::{FromIterator, Iterator};

#[derive(Debug, Default)]
pub struct Table {
    pub topic: Option<String>,
    pub header: Option<Row>,
    pub rows: Vec<Row>,
}

impl Table {
    pub fn push_row(&mut self, row: impl Into<Row>) {
        self.rows.push(row.into());
    }

    /// Pushes an entire table to this table. This will panic if the tables
    /// are not of the same size.
    ///
    /// The topic of the pused table will be discarded.
    /// The header row, (if any), will be added to this table with Style header.
    pub fn push_table(&mut self, other: Table) {
        self.rows
            .reserve(other.rows.len() + other.header.as_ref().map(|_| 1).unwrap_or(0));
        if let Some(header) = other.header {
            self.push_row(header.with_style(RowStyle::Header));
        }

        let mut new_rows = other.rows;
        self.rows.append(&mut new_rows);
    }

    pub fn set_topic(&mut self, s: impl Into<String>) {
        self.topic = Some(s.into());
    }

    pub fn set_header(&mut self, header: impl IntoIterator<Item = Cell>) {
        self.header = Some(
            header
                .into_iter()
                .collect::<Row>()
                .with_style(RowStyle::Header),
        );
    }

    pub fn to_pdf(&self, title: impl AsRef<str>) -> Result<Vec<u8>, Error> {
        let mut pdf = Helper::new_a4(title.as_ref())?;

        pdf.new_line();
        pdf.font_size(16);
        pdf.write_line(title.as_ref());
        pdf.new_line();
        pdf.font_size(8);
        pdf.write_table(&self);

        let mut buf = std::io::BufWriter::new(Vec::new());
        pdf.write_to(&mut buf)?;
        buf.into_inner()
            .map_err(|err| Error::IntoBuffer(format!("{}", err)))
    }

    pub fn to_csv(&self) -> Result<Vec<u8>, Error> {
        let mut writer = csv::Writer::from_writer(vec![]);

        if let Some(ref header) = self.header {
            writer.write_record(&header.cells)?;
        }

        for row in &self.rows {
            writer.write_record(&row.cells)?;
        }

        writer
            .into_inner()
            .map_err(|err| Error::IntoBuffer(err.to_string()))
    }
}

impl FromIterator<Row> for Table {
    fn from_iter<It: IntoIterator<Item = Row>>(iter: It) -> Self {
        Self {
            topic: None,
            header: None,
            rows: iter.into_iter().collect(),
        }
    }
}