Cotton code
258 lines · 12.2 KB · RustRaw
//! Synthetic lab-report PDFs for tests: an invented person, invented//! values, laid out like a lab's five-column report. A plain text PDF//! (Helvetica, WinAnsi), so the reader is tested on real PDF bytes and no//! real report is ever needed./// One piece of text: `x` from the left, `y` from the TOP, in points.#[derive(Debug, Clone, PartialEq)]pub struct Text {    pub x: f32,    pub y: f32,    pub size: f32,    pub text: String,}pub fn text(x: f32, y: f32, words: &str) -> Text {    Text { x, y, size: 9.0, text: words.to_string() }}/// A4, in points.const WIDTH: f32 = 595.0;const HEIGHT: f32 = 842.0;/// WinAnsi bytes of `text`, escaped for a PDF string.fn pdf_string(text: &str) -> Vec<u8> {    let mut out = Vec::new();    for c in text.chars() {        let byte = match c {            '(' | ')' | '\\' => {                out.push(b'\\');                c as u8            }            'µ' | 'μ' => 0xB5,            '³' => 0xB3,            '²' => 0xB2,            '°' => 0xB0,            '–' => 0x96,            c if (c as u32) < 0x80 => c as u8,            c if (c as u32) < 0x100 => c as u32 as u8,            _ => b'?',        };        out.push(byte);    }    out}/// A PDF of `pages`, each a list of texts.pub fn pdf(pages: &[Vec<Text>]) -> Vec<u8> {    let mut objects: Vec<Vec<u8>> = Vec::new();    // 1 catalog, 2 pages, 3 font, then per page: page, content.    let kids: Vec<String> = (0..pages.len()).map(|at| format!("{} 0 R", 4 + at * 2)).collect();    objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());    objects.push(format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).into_bytes());    objects.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_vec());    for (at, page) in pages.iter().enumerate() {        let content_id = 5 + at * 2;        objects.push(format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {WIDTH} {HEIGHT}] /Resources << /Font << /F1 3 0 R >> >> /Contents {content_id} 0 R >>").into_bytes());        let mut stream = Vec::new();        for piece in page {            stream.extend(format!("BT /F1 {} Tf 1 0 0 1 {:.2} {:.2} Tm (", piece.size, piece.x, HEIGHT - piece.y).into_bytes());            stream.extend(pdf_string(&piece.text));            stream.extend(b") Tj ET\n");        }        let mut object = format!("<< /Length {} >>\nstream\n", stream.len()).into_bytes();        object.extend(stream);        object.extend(b"endstream");        objects.push(object);    }    file_of(&objects)}/// Objects 1.. into a PDF file: `objects[0]` is the catalog.fn file_of(objects: &[Vec<u8>]) -> Vec<u8> {    let mut out = b"%PDF-1.4\n".to_vec();    let mut offsets = Vec::new();    for (at, object) in objects.iter().enumerate() {        offsets.push(out.len());        out.extend(format!("{} 0 obj\n", at + 1).into_bytes());        out.extend(object);        out.extend(b"\nendobj\n");    }    let xref = out.len();    out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).into_bytes());    for offset in offsets {        out.extend(format!("{offset:010} 00000 n \n").into_bytes());    }    out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).into_bytes());    out}fn stream_object(dict: &str, stream: &[u8]) -> Vec<u8> {    let mut object = format!("<< {dict} /Length {} >>\nstream\n", stream.len()).into_bytes();    object.extend(stream);    object.extend(b"\nendstream");    object}/// The same pages drawn the way a report generator of the HTML-to-PDF kind/// draws them: the media box on the page tree (inherited), each page's text/// inside a form XObject under a flipped matrix (`1 0 0 -1 0 H cm`, text/// matrices `1 0 0 -1 x y`), a CID font (Identity-H, two-byte codes, a/// ToUnicode map and `W` widths), and a margin note drawn rotated.pub fn pdf_in_forms(pages: &[Vec<Text>]) -> Vec<u8> {    // Every character used, a two-byte code each.    let mut alphabet: Vec<char> = pages.iter().flatten().flat_map(|piece| piece.text.chars()).chain("Printed sideways".chars()).collect();    alphabet.sort();    alphabet.dedup();    let code = |c: char| 0x0100 + alphabet.iter().position(|known| *known == c).expect("in the alphabet") as u32;    let width = |c: char| match c as u32 {        32..=126 => [            278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667,            611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584,        ][(c as u32 - 32) as usize],        _ => 556,    };    let hex = |text: &str| text.chars().map(|c| format!("{:04X}", code(c))).collect::<String>();    // 1 catalog, 2 pages, 3 font, 4 descendant, 5 ToUnicode; per page: page, content, form.    let kids: Vec<String> = (0..pages.len()).map(|at| format!("{} 0 R", 6 + at * 3)).collect();    let mut objects: Vec<Vec<u8>> = vec![        b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),        format!("<< /Type /Pages /Kids [{}] /Count {} /MediaBox [0 0 {WIDTH} {HEIGHT}] >>", kids.join(" "), pages.len()).into_bytes(),        b"<< /Type /Font /Subtype /Type0 /BaseFont /InventedSans /Encoding /Identity-H /DescendantFonts [4 0 R] /ToUnicode 5 0 R >>".to_vec(),    ];    let widths: Vec<String> = alphabet.iter().map(|c| width(*c).to_string()).collect();    objects.push(format!("<< /Type /Font /Subtype /CIDFontType2 /BaseFont /InventedSans /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /DW 1000 /W [256 [{}]] >>", widths.join(" ")).into_bytes());    let mut cmap = String::from("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");    cmap.push_str(&format!("{} beginbfchar\n", alphabet.len()));    for c in &alphabet {        let mut units = [0u16; 2];        let utf16: String = c.encode_utf16(&mut units).iter().map(|unit| format!("{unit:04X}")).collect();        cmap.push_str(&format!("<{:04X}> <{utf16}>\n", code(*c)));    }    cmap.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");    objects.push(stream_object("", cmap.as_bytes()));    for (at, page) in pages.iter().enumerate() {        let (page_id, content_id, form_id) = (6 + at * 3, 7 + at * 3, 8 + at * 3);        let _ = page_id;        objects.push(format!("<< /Type /Page /Parent 2 0 R /Resources << /XObject << /Fm1 {form_id} 0 R >> >> /Contents {content_id} 0 R >>").into_bytes());        objects.push(stream_object("", b"q 1 0 0 1 0 0 cm /Fm1 Do Q\n"));        let mut form = format!("q 1 0 0 -1 0 {HEIGHT} cm\n");        for piece in page {            form.push_str(&format!("BT /F1 {} Tf 1 0 0 -1 {:.2} {:.2} Tm <{}> Tj ET\n", piece.size, piece.x, piece.y, hex(&piece.text)));        }        form.push_str("Q\n");        // A note up the left margin, read bottom to top.        form.push_str(&format!("q 0 1 -1 0 12 400 cm BT /F1 6 Tf 0 0 Td <{}> Tj ET Q\n", hex("Printed sideways")));        objects.push(stream_object(&format!("/Type /XObject /Subtype /Form /BBox [0 0 {WIDTH} {HEIGHT}] /Resources << /Font << /F1 3 0 R >> >>"), form.as_bytes()));    }    file_of(&objects)}/// What a synthetic report holds.#[derive(Debug, Clone)]pub struct Sample {    pub name: String,    pub age_sex: String,    pub order: String,    pub status: String,    pub collected: String,    pub reported: String,    /// (panel, [(name, result, unit, interval lines, method)]).    pub panels: Vec<(String, Vec<(String, String, String, Vec<String>, String)>)>,    /// A paragraph after the first panel, laid across the columns.    pub interpretation: bool,}impl Sample {    /// An invented person's lipid and sugar report.    pub fn invented(name: &str, order: &str, status: &str) -> Sample {        let row = |n: &str, r: &str, u: &str, i: &[&str], m: &str| (n.to_string(), r.to_string(), u.to_string(), i.iter().map(|s| s.to_string()).collect(), m.to_string());        Sample {            name: name.into(),            age_sex: "41 Y / Female".into(),            order: order.into(),            status: status.into(),            collected: "12/Mar/2024 08:15 AM".into(),            reported: "12/Mar/2024 06:40 PM".into(),            panels: vec![                (                    "LIPID PROFILE".into(),                    vec![                        row("Cholesterol - Total", "212", "mg/dL", &["Desirable : < 200", "Borderline High : 200 - 239", "High : >= 240"], "Enzymatic"),                        row("HDL Cholesterol - Direct", "48", "mg/dL", &["> 40"], "Direct"),                        row("Triglycerides", "150", "mg/dL", &["< 150"], "GPO-PAP"),                    ],                ),                (                    "DIABETES".into(),                    vec![                        row("HbA1c", "5.8", "%", &["Normal : < 5.7", "Prediabetes : 5.7 - 6.4", "Diabetes : >= 6.5"], "HPLC"),                        row("Average Blood Glucose (ABG)", "120", "mg/dL", &["90 - 120"], "Calculated"),                    ],                ),            ],            interpretation: true,        }    }    /// The report's pages: a header block on each, the table head repeated.    pub fn pages(&self) -> Vec<Vec<Text>> {        let header = |out: &mut Vec<Text>| {            out.push(text(40.0, 40.0, "Customer Name"));            out.push(text(130.0, 40.0, &format!(": {}", self.name)));            out.push(text(320.0, 40.0, "Order Id"));            out.push(text(400.0, 40.0, &format!(": {}", self.order)));            out.push(text(40.0, 52.0, "Age/Gender"));            out.push(text(130.0, 52.0, &format!(": {}", self.age_sex)));            out.push(text(320.0, 52.0, "Sample Type"));            out.push(text(400.0, 52.0, ": Serum"));            out.push(text(40.0, 64.0, "Collected Via"));            out.push(text(130.0, 64.0, ": Home Collection"));            out.push(text(320.0, 64.0, "Report Status"));            out.push(text(400.0, 64.0, &format!(": {}", self.status)));            out.push(text(40.0, 76.0, "Collected On"));            out.push(text(130.0, 76.0, &format!(": {}", self.collected)));            out.push(text(320.0, 76.0, "Reported On"));            out.push(text(400.0, 76.0, &format!(": {}", self.reported)));            for (x, head) in [(40.0, "Test Name"), (250.0, "Result"), (310.0, "Unit"), (370.0, "Bio. Ref. Interval"), (500.0, "Method")] {                out.push(text(x, 100.0, head));            }        };        let mut pages = Vec::new();        for (at, (panel, rows)) in self.panels.iter().enumerate() {            let mut page = Vec::new();            header(&mut page);            let mut y = 116.0;            page.push(text(40.0, y, panel));            y += 14.0;            for (name, result, unit, interval, method) in rows {                page.push(text(40.0, y, name));                page.push(text(250.0, y, result));                page.push(text(310.0, y, unit));                page.push(text(500.0, y, method));                for (n, line) in interval.iter().enumerate() {                    page.push(text(370.0, y + n as f32 * 11.0, line));                }                y += 11.0 * interval.len().max(1) as f32 + 4.0;            }            if self.interpretation && at == 0 {                y += 8.0;                page.push(text(40.0, y, "Interpretation :"));                page.push(text(40.0, y + 11.0, "These values are read together with the person's history and other results by the doctor who asked"));                page.push(text(40.0, y + 22.0, "for the test."));            }            page.push(text(260.0, 800.0, &format!("Page {} of {}", at + 1, self.panels.len())));            pages.push(page);        }        pages    }    pub fn pdf(&self) -> Vec<u8> {        pdf(&self.pages())    }    /// The same report drawn inside forms, flipped, in a CID font ([`pdf_in_forms`]).    pub fn pdf_in_forms(&self) -> Vec<u8> {        pdf_in_forms(&self.pages())    }}