isis-report-lib 0.2.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
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
//! Typed report builder and one-shot render/export entry points.
//!
//! [`Report`] owns a validated payload and the prepared dataset, layout and
//! metadata produced by the same pipeline used by the free functions and by
//! [`ReportService`]. The builder is additive sugar: it
//! does not change payload validation, formatting or export semantics.
//!
//! ```
//! use isis_report_lib::{CsvOptions, RenderOptions, Report};
//! use serde_json::json;
//!
//! let report = Report::builder()
//!     .title("Sales")
//!     .locale("en-US")
//!     .layout(json!({
//!         "product": {"label": "Product", "format_mask": "str"},
//!         "total": {"label": "Total", "format_mask": "currency"}
//!     }))
//!     .data(json!([{"product": "Pen", "total": 12.5}]))
//!     .build()?;
//!
//! let html = report.render_html(&RenderOptions::default())?;
//! let csv = report.export_csv(CsvOptions::default())?;
//! assert!(html.contains("Sales"));
//! assert!(csv.contains("Pen"));
//! # Ok::<(), isis_report_lib::Error>(())
//! ```

use std::borrow::Cow;

use indexmap::IndexMap;

use crate::error::{Error, Result};
use crate::export::{build_workbook, collect_tables, render_csv};
use crate::options::{CsvOptions, RenderOptions, TextOptions, XlsxOptions};
use crate::payload::{Limits, Meta};
use crate::service::{prepare_report, PreparedReport, ReportService};
use crate::text::{sanitize_text, wrap_report_text};
use crate::value::Value;

/// Builder for a validated [`Report`].
///
/// Metadata keys follow the payload schema (`title`, `sub_title`, `company`,
/// `locale`, `currency`, `direction`, ...). `layout`, `data` and `sections`
/// accept anything that converts into [`Value`], including
/// `serde_json::Value`, [`Value`] and index maps.
#[derive(Debug, Clone, Default)]
pub struct ReportBuilder {
    meta: IndexMap<String, Value>,
    layout: Option<Value>,
    data: Option<Value>,
    rows: Vec<Value>,
    sections: Option<Value>,
    extra_sections: Vec<Value>,
    limits: Option<Limits>,
}

fn extend_array(value: Option<Value>, extra: Vec<Value>, method: &str, key: &str) -> Result<Option<Value>> {
    if extra.is_empty() {
        return Ok(value);
    }
    match value {
        None => Ok(Some(Value::Array(extra))),
        Some(Value::Array(mut array)) => {
            array.extend(extra);
            Ok(Some(Value::Array(array)))
        }
        Some(_) => Err(Error::option(format!(
            "{method}() requires the existing {key} value to be an array"
        ))),
    }
}

impl ReportBuilder {
    /// Start an empty builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the report title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.meta.insert("title".to_string(), Value::String(title.into()));
        self
    }

    /// Set the report subtitle (payload key `sub_title`).
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.meta.insert("sub_title".to_string(), Value::String(subtitle.into()));
        self
    }

    /// Set the company shown in the header.
    pub fn company(mut self, company: impl Into<String>) -> Self {
        self.meta.insert("company".to_string(), Value::String(company.into()));
        self
    }

    /// Set the BCP-47 locale used by formatting and localized labels.
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.meta.insert("locale".to_string(), Value::String(locale.into()));
        self
    }

    /// Set the default currency (ISO-4217 code).
    pub fn currency(mut self, currency: impl Into<String>) -> Self {
        self.meta.insert("currency".to_string(), Value::String(currency.into()));
        self
    }

    /// Set the text direction (`ltr` or `rtl`).
    pub fn direction(mut self, direction: impl Into<String>) -> Self {
        self.meta.insert("direction".to_string(), Value::String(direction.into()));
        self
    }

    /// Set any other metadata key accepted by the payload schema.
    pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.meta.insert(key.into(), value.into());
        self
    }

    /// Replace the hierarchical layout.
    pub fn layout(mut self, layout: impl Into<Value>) -> Self {
        self.layout = Some(layout.into());
        self
    }

    /// Replace the report data array. Clears any rows queued with [`row`](Self::row).
    pub fn data(mut self, data: impl Into<Value>) -> Self {
        self.data = Some(data.into());
        self.rows.clear();
        self
    }

    /// Append one data row.
    ///
    /// When `data` was set to a non-array value, [`build`](Self::build) fails
    /// instead of silently wrapping it in an array.
    pub fn row(mut self, row: impl Into<Value>) -> Self {
        self.rows.push(row.into());
        self
    }

    /// Replace the data array from an iterator of rows.
    pub fn rows<I, T>(mut self, rows: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Value>,
    {
        self.data = Some(Value::Array(rows.into_iter().map(Into::into).collect()));
        self.rows.clear();
        self
    }

    /// Replace the composed `sections` array. Clears sections queued with
    /// [`section`](Self::section).
    pub fn sections(mut self, sections: impl Into<Value>) -> Self {
        self.sections = Some(sections.into());
        self.extra_sections.clear();
        self
    }

    /// Append one composed section.
    ///
    /// When `sections` was set to a non-array value, [`build`](Self::build)
    /// fails instead of silently wrapping it in an array.
    pub fn section(mut self, section: impl Into<Value>) -> Self {
        self.extra_sections.push(section.into());
        self
    }

    /// Apply operator quotas. Payload `meta.limits` can only tighten them.
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = Some(limits);
        self
    }

    /// Validate the payload and build a [`Report`].
    ///
    /// Validation matches [`normalize_payload`](crate::normalize_payload):
    /// unknown keys, mistyped metadata and non-array `data`/`sections` fail
    /// here instead of at the first export.
    pub fn build(self) -> Result<Report> {
        let data = extend_array(self.data, self.rows, "row", "data")?;
        let sections = extend_array(self.sections, self.extra_sections, "section", "sections")?;
        let mut payload = IndexMap::new();
        if !self.meta.is_empty() {
            payload.insert("meta".to_string(), Value::Object(self.meta));
        }
        if let Some(layout) = self.layout {
            payload.insert("layout".to_string(), layout);
        }
        if let Some(data) = data {
            payload.insert("data".to_string(), data);
        }
        if let Some(sections) = sections {
            payload.insert("sections".to_string(), sections);
        }
        let payload = Value::Object(payload);
        let prepared = prepare_report(&payload, self.limits)?;
        Ok(Report {
            payload,
            prepared,
            limits: self.limits,
        })
    }
}

/// A validated report payload with its prepared dataset, layout and metadata.
///
/// Exports reuse the prepared report built by [`Report::builder`] or
/// [`Report::try_from`]. Options that carry explicit limits re-run the payload
/// checks with the tighter caps before exporting.
#[derive(Debug, Clone)]
pub struct Report {
    payload: Value,
    prepared: PreparedReport,
    limits: Option<Limits>,
}

impl Report {
    /// Start a builder.
    pub fn builder() -> ReportBuilder {
        ReportBuilder::new()
    }

    /// Validate an existing payload.
    pub fn from_value(payload: Value) -> Result<Self> {
        Self::try_from(payload)
    }

    /// Validate a JSON payload.
    pub fn from_json(payload: serde_json::Value) -> Result<Self> {
        Self::from_value(Value::from_json(payload))
    }

    /// Parse and validate a `.toon` payload.
    pub fn from_toon(text: &str) -> Result<Self> {
        Self::from_value(crate::toon::parse_toon(text)?)
    }

    /// Build a report from an iterator of rows, inferring the layout.
    pub fn from_rows<I, T>(rows: I) -> Result<Self>
    where
        I: IntoIterator<Item = T>,
        T: Into<Value>,
    {
        Self::builder().rows(rows).build()
    }

    /// The validated payload.
    pub fn payload(&self) -> &Value {
        &self.payload
    }

    /// The prepared dataset, layout and metadata.
    pub fn prepared(&self) -> &PreparedReport {
        &self.prepared
    }

    /// The normalized metadata (including generated defaults).
    pub fn meta(&self) -> &Meta {
        &self.prepared.meta
    }

    fn prepared_with(&self, limits: Option<Limits>) -> Result<Cow<'_, PreparedReport>> {
        let effective = limits.map(|extra| match self.limits {
            Some(base) => base.tightened_with(extra),
            None => extra,
        });
        match effective {
            Some(limits) => Ok(Cow::Owned(prepare_report(&self.payload, Some(limits))?)),
            None => Ok(Cow::Borrowed(&self.prepared)),
        }
    }

    /// Render the HTML output with explicit options.
    pub fn render_html(&self, options: &RenderOptions) -> Result<String> {
        let prepared = self.prepared_with(options.limits)?;
        let service = ReportService {
            template_dir: options.template_dir.clone(),
            template_name: options.template_name.clone(),
            inline_css: options.inline_css,
            limits: options.limits,
            #[cfg(feature = "pdf")]
            pdf_options: None,
        };
        service.render_prepared_html(&prepared)
    }

    /// Render the HTML output with default options.
    pub fn render_html_default(&self) -> Result<String> {
        self.render_html(&RenderOptions::default())
    }

    /// Export CSV with explicit options.
    pub fn export_csv(&self, options: CsvOptions) -> Result<String> {
        let prepared = self.prepared_with(options.limits)?;
        let meta = prepared.meta.to_value();
        let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
        let text = render_csv(&tables, &summaries, Some(&meta), options.delimiter)?;
        Ok(if options.bom { format!("\u{feff}{text}") } else { text })
    }

    /// Render the visible-only plain-text export with explicit options.
    pub fn export_text(&self, options: TextOptions) -> Result<String> {
        let prepared = self.prepared_with(options.limits)?;
        let meta = prepared.meta.to_value();
        let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
        let text = render_csv(&tables, &summaries, Some(&meta), ',')?;
        let text = if options.sanitize { sanitize_text(&text) } else { text };
        Ok(wrap_report_text(&text))
    }

    /// Shortcut for [`export_text`](Self::export_text) with default options and
    /// an explicit sanitize flag.
    pub fn render_text(&self, sanitize: bool) -> Result<String> {
        self.export_text(TextOptions::default().with_sanitize(sanitize))
    }

    /// Export an `.xlsx` workbook with explicit options.
    pub fn export_xlsx(&self, options: XlsxOptions) -> Result<Vec<u8>> {
        let prepared = self.prepared_with(options.limits)?;
        let meta = prepared.meta.to_value();
        let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
        build_workbook(&tables, &summaries, Some(&meta))
    }

    /// Generate a PDF with default HTML render options. Requires the `pdf`
    /// feature and a Chromium/Chrome installation.
    #[cfg(feature = "pdf")]
    pub fn export_pdf(&self, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
        self.export_pdf_with(&RenderOptions::default(), options)
    }

    /// Generate a PDF with explicit HTML and PDF options.
    #[cfg(feature = "pdf")]
    pub fn export_pdf_with(&self, render: &RenderOptions, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
        let prepared = self.prepared_with(render.limits)?;
        let service = ReportService {
            template_dir: render.template_dir.clone(),
            template_name: render.template_name.clone(),
            inline_css: render.inline_css,
            limits: render.limits,
            pdf_options: Some(options.clone()),
        };
        service.generate_pdf_prepared(&prepared, options)
    }

    /// Generate a PDF asynchronously with default HTML render options.
    #[cfg(feature = "pdf")]
    pub async fn export_pdf_async(&self, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
        self.export_pdf_with_async(&RenderOptions::default(), options).await
    }

    /// Generate a PDF asynchronously with explicit HTML and PDF options.
    #[cfg(feature = "pdf")]
    pub async fn export_pdf_with_async(&self, render: &RenderOptions, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
        let prepared = self.prepared_with(render.limits)?;
        let service = ReportService {
            template_dir: render.template_dir.clone(),
            template_name: render.template_name.clone(),
            inline_css: render.inline_css,
            limits: render.limits,
            pdf_options: Some(options.clone()),
        };
        service.generate_pdf_prepared_async(&prepared, options).await
    }
}

impl TryFrom<Value> for Report {
    type Error = crate::error::Error;

    fn try_from(payload: Value) -> Result<Self> {
        let prepared = prepare_report(&payload, None)?;
        Ok(Self {
            payload,
            prepared,
            limits: None,
        })
    }
}

impl TryFrom<serde_json::Value> for Report {
    type Error = crate::error::Error;

    fn try_from(payload: serde_json::Value) -> Result<Self> {
        Self::from_json(payload)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::payload::Meta;
    use serde_json::json;

    fn sample() -> ReportBuilder {
        Report::builder()
            .title("Sales")
            .subtitle("Quarterly")
            .company("ACME")
            .locale("en-US")
            .currency("USD")
            .layout(json!({
                "product": {"label": "Product", "format_mask": "str"},
                "total": {"label": "Total", "format_mask": "currency"}
            }))
    }

    #[test]
    fn builder_sets_metadata_and_validates() {
        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();

        assert_eq!(report.meta().title(), Some("Sales"));
        assert_eq!(report.meta().sub_title(), Some("Quarterly"));
        assert_eq!(report.meta().company(), Some("ACME"));
        assert_eq!(report.meta().locale(), "en-US");
        assert_eq!(report.meta().currency(), Some("USD"));
        assert_eq!(report.meta().direction(), "ltr");
        assert_eq!(
            report.payload().get("meta").and_then(|m| m.get("title")).and_then(Value::as_str),
            Some("Sales")
        );
        assert!(report.prepared().dataset.get("groups").is_some());
    }

    #[test]
    fn builder_rejects_invalid_payloads() {
        assert!(Report::builder().layout(json!("not-an-object")).build().is_err());
        assert!(Report::builder().data(json!({"not": "an array"})).build().is_err());
        assert!(Report::builder().sections(json!("not-an-array")).build().is_err());
        assert!(Report::builder().meta("bogus", 1).build().is_err());
        assert!(Report::builder()
            .limits(Limits {
                max_rows: Some(1),
                max_bytes: None
            })
            .data(json!([{"a": 1}, {"a": 2}]))
            .build()
            .is_err());
    }

    #[test]
    fn rows_and_sections_append() {
        let report = Report::builder()
            .title("Rows")
            .row(json!({"a": 1}))
            .row(json!({"a": 2}))
            .build()
            .unwrap();
        assert_eq!(
            report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
            Some(2)
        );

        let report = Report::builder().data(json!([{"b": 0}])).row(json!({"a": 1})).build().unwrap();
        assert_eq!(
            report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
            Some(2)
        );

        let error = Report::builder()
            .data(json!({"template": "summary"}))
            .row(json!({"a": 1}))
            .build()
            .unwrap_err();
        assert!(error.to_string().contains("row() requires"));

        let rows = vec![json!({"a": 1}), json!({"a": 2})];
        let report = Report::from_rows(rows).unwrap();
        assert_eq!(report.meta().title(), None);

        // `data()` replaces rows queued earlier.
        let report = Report::builder().row(json!({"a": 1})).data(json!([{"b": 2}])).build().unwrap();
        assert_eq!(
            report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
            Some(1)
        );

        let section = json!({"type": "table", "data": [{"a": 1}]});
        let report = Report::builder()
            .sections(json!([section.clone()]))
            .section(json!({"type": "table", "data": [{"a": 2}]}))
            .build()
            .unwrap();
        assert_eq!(
            report.prepared().dataset.get("sections").and_then(Value::as_array).map(Vec::len),
            Some(2)
        );

        let error = Report::builder()
            .sections(json!({"type": "text", "paragraphs": ["x"]}))
            .section(section)
            .build()
            .unwrap_err();
        assert!(error.to_string().contains("section() requires"));
    }

    #[test]
    fn render_and_export_paths() {
        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();

        let html = report.render_html_default().unwrap();
        assert!(html.contains("Sales"));
        assert!(html.contains("Pen"));

        #[cfg(feature = "email")]
        {
            let html = report.render_html(&RenderOptions::default().with_inline_css(true)).unwrap();
            assert!(html.contains("<style") || html.contains("style="));
        }
        #[cfg(not(feature = "email"))]
        {
            let error = report.render_html(&RenderOptions::default().with_inline_css(true)).unwrap_err();
            assert!(error.to_string().contains("email"));
        }

        let csv = report.export_csv(CsvOptions::default()).unwrap();
        assert!(csv.contains("Pen"));
        let csv = report.export_csv(CsvOptions::new().with_delimiter(';').with_bom(true)).unwrap();
        assert!(csv.starts_with('\u{feff}'));
        assert!(csv.contains(';'));

        let text = report.render_text(true).unwrap();
        assert!(text.contains("Pen"));
        assert!(report.render_text(false).unwrap().contains("Pen"));
        let text = report.export_text(TextOptions::new().with_sanitize(false)).unwrap();
        assert!(text.contains("Pen"));
    }

    #[test]
    fn export_options_tighten_limits() {
        let report = sample()
            .data(json!([{"product": "Pen", "total": 12.5}, {"product": "Pencil", "total": 3.0}]))
            .build()
            .unwrap();

        let csv = CsvOptions::new().with_limits(Limits {
            max_rows: Some(1),
            max_bytes: None,
        });
        assert!(report.export_csv(csv).is_err());
        assert!(report
            .export_xlsx(XlsxOptions::new().with_limits(Limits {
                max_rows: Some(1),
                max_bytes: None
            }))
            .is_err());

        let render = RenderOptions::new().with_limits(Limits {
            max_rows: Some(1),
            max_bytes: None,
        });
        assert!(report.render_html(&render).is_err());
        assert!(report.render_html(&RenderOptions::default()).is_ok());
        assert!(report
            .export_text(TextOptions::new().with_limits(Limits {
                max_rows: Some(1),
                max_bytes: None
            }))
            .is_err());
    }

    #[cfg(feature = "xlsx")]
    #[test]
    fn exports_xlsx_bytes() {
        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
        let bytes = report.export_xlsx(XlsxOptions::default()).unwrap();
        assert!(bytes.starts_with(b"PK"));
    }

    #[test]
    fn parses_json_value_and_toon() {
        let report = Report::from_json(json!({
            "meta": {"title": "JSON"},
            "data": [{"a": 1}]
        }))
        .unwrap();
        assert_eq!(report.meta().title(), Some("JSON"));

        let report = Report::from_value(Value::from_json(json!({
            "meta": {"title": "Value"},
            "data": [{"a": 1}]
        })))
        .unwrap();
        assert_eq!(report.meta().title(), Some("Value"));

        let report = Report::from_toon("meta:\n  title: TOON\ndata[1]{a}:\n  1").unwrap();
        assert_eq!(report.meta().title(), Some("TOON"));

        assert!(Report::try_from(Value::from_json(json!({"bogus": true}))).is_err());
        assert!(Report::try_from(json!({"bogus": true})).is_err());
        assert!(Report::from_toon("meta: [").is_err());

        let text = include_str!("../examples/sales_order.toon");
        let report = Report::from_toon(text).unwrap();
        assert!(report.meta().title().is_some());
    }

    #[test]
    fn meta_chainable_setters() {
        let meta = Meta::new()
            .with_title("T")
            .with_subtitle("S")
            .with_company("C")
            .with_locale("pt-BR")
            .with_currency("BRL")
            .with_direction("rtl")
            .with_accent_color("#123456")
            .with_source_note("Source")
            .with_meta("mode", "summary");
        assert_eq!(meta.title(), Some("T"));
        assert_eq!(meta.sub_title(), Some("S"));
        assert_eq!(meta.company(), Some("C"));
        assert_eq!(meta.locale(), "pt-BR");
        assert_eq!(meta.currency(), Some("BRL"));
        assert_eq!(meta.direction(), "rtl");
        assert_eq!(meta.accent_color(), Some("#123456"));
        assert_eq!(meta.source_note(), Some("Source"));
        assert_eq!(meta.mode(), Some("summary"));
    }

    #[cfg(feature = "pdf")]
    #[test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    fn exports_real_pdfs() {
        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
        let options = crate::pdf_backend::PdfOptions::default();

        let pdf = report.export_pdf(&options).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));

        let pdf = report
            .export_pdf_with(&RenderOptions::default().with_template_name("tabular.jinja"), &options)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF-"));

        let pdf = futures::executor::block_on(report.export_pdf_async(&options)).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));

        let pdf = futures::executor::block_on(report.export_pdf_with_async(&RenderOptions::default(), &options)).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        crate::pdf_backend::shutdown_pdf_pool();
    }
}