Three statements in one file

Four sheets holding three customer statements. Each one claims the sheets it runs to, states who it is for and how many copies are owed, and carries its own data file.

Rust write_document_parts.rs 564 lines
  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
//! Writes three customer statements into one file, and says in the file where
//! each of them starts.
//!
//! A print shop that receives a single PDF of four sheets has no way of knowing
//! that it holds three statements rather than one long one, nor how many copies
//! each recipient is owed. That is what a job ticket beside the file is usually
//! for. Here the file says it itself: a hierarchy of document parts, one part
//! per statement, each claiming its own run of pages, stating what a press
//! needs to know about it, and carrying the data file that belongs to it.
//!
//! Both sets of words are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn.
//!
//! Usage: `cargo run --example write_document_parts -- tmp/parts.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_document_parts`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::layout::{Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table};
use hqf_pdf::metadata::attachment::{Attachment, Relationship};
use hqf_pdf::{
    Align, AttachmentHandle, Document, DocumentPart, DocumentParts, Error, Font, FontHandle, Page,
    PartData, PartValue, Rgb, TextFlow, Version,
};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

use language::Language;

/// The font the page is set in when the caller names none: the one committed
/// for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The words the pages are written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the file as a whole is called.
    title: &'static str,
    /// What the file carries, said once at the top of the first sheet.
    lead: &'static str,
    /// What the hierarchy says, said in grey at the foot of the first sheet.
    note: &'static str,
    /// The word a statement is called by.
    statement: &'static str,
    /// The word a customer number is introduced by.
    customer: &'static str,
    /// The word a sheet is counted by.
    sheet: &'static str,
    /// Who each of the three statements is for.
    recipients: [&'static str; 3],
    /// Where each of them is sent.
    towns: [&'static str; 3],
    /// The country every recipient is in.
    country: &'static str,
    /// The two column headings of a statement.
    columns: [&'static str; 2],
    /// What the three lines of a statement are called.
    lines: [&'static str; 3],
    /// The label on the total row.
    total: &'static str,
    /// The heading of the terms sheet.
    terms_title: &'static str,
    /// What the terms sheet says.
    terms: &'static str,
    /// What the file carried beside each statement holds.
    carried: &'static str,
}

impl Words {
    /// The words the pages are written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The pages in English.
const ENGLISH: Words = Words {
    title: "Three statements, one file",
    lead: "The four sheets below are three statements, not one. Nothing drawn \
           on them says where one recipient ends and the next begins — the \
           file says it, beside the pages rather than on them, so a press can \
           print and cut this run without a second file explaining it.",
    note: "Each part claims its own run of sheets, states the customer it is \
           for and the number of copies owed, and carries the data file that \
           belongs to it and to no other part. A reader shows one document; a \
           press reads three.",
    statement: "Statement",
    customer: "Customer",
    sheet: "Sheet",
    recipients: ["Baker and Sons", "Halden Joinery", "Westmill Dairy"],
    towns: ["Bristol", "Kendal", "Truro"],
    country: "United Kingdom",
    columns: ["Description", "Amount"],
    lines: [
        "Goods delivered in July",
        "Carriage, four crates",
        "Storage, one month",
    ],
    total: "Total",
    terms_title: "Terms of payment",
    terms: "Payment falls due thirty days from the date this statement was \
            posted. An amount still owing after that date carries interest at \
            three times the legal rate, and a fixed sum of forty euros towards \
            the cost of recovering it. Payment is made to the account named on \
            the statement, quoting the customer number.",
    carried: "The statement as a data file",
};

/// The pages in French.
const FRENCH: Words = Words {
    title: "Trois relevés, un seul fichier",
    lead: "Les quatre feuillets ci-dessous sont trois relevés, et non un seul. \
           Rien de ce qui est dessiné dessus ne dit où finit un destinataire \
           et où commence le suivant : c'est le fichier qui le dit, à côté des \
           pages plutôt que dessus, de sorte qu'un imprimeur tire et coupe ce \
           lot sans un second fichier pour le lui expliquer.",
    note: "Chaque partie revendique sa propre suite de feuillets, énonce le \
           client à qui elle s'adresse et le nombre d'exemplaires dus, et \
           emporte le fichier de données qui lui appartient et qui \
           n'appartient à aucune autre. Un lecteur montre un document ; un \
           imprimeur en lit trois.",
    statement: "Relevé",
    customer: "Client",
    sheet: "Feuillet",
    recipients: [
        "Boulangerie Petit",
        "Menuiserie Vallon",
        "Laiterie du Coteau",
    ],
    towns: ["Aix-en-Provence", "Annecy", "Quimper"],
    country: "France",
    columns: ["Désignation", "Montant"],
    lines: [
        "Marchandises livrées en juillet",
        "Transport, quatre caisses",
        "Entreposage, un mois",
    ],
    total: "Total",
    terms_title: "Conditions de règlement",
    terms: "Le règlement est exigible trente jours après la date d'envoi du \
            présent relevé. Toute somme encore due passé cette date porte \
            intérêt au triple du taux légal, augmenté d'une indemnité \
            forfaitaire de quarante euros pour frais de recouvrement. Le \
            règlement est fait sur le compte indiqué au relevé, sous le \
            numéro de client.",
    carried: "Le relevé sous forme de fichier de données",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// The left edge of everything on the pages.
const LEFT: f64 = 72.0;

/// How wide a block of text, and a statement, are.
const WIDTH: f64 = 451.0;

/// The number each customer is known by.
const NUMBERS: [&str; 3] = ["4711", "4712", "4713"];

/// How many copies of each statement the run owes.
const COPIES: [i64; 3] = [2, 1, 3];

/// When each statement was posted.
const POSTED: [&str; 3] = [
    "2026-08-03T09:15:00+02:00",
    "2026-08-03T09:16:00+02:00",
    "2026-08-03T09:17:00+02:00",
];

/// What each statement charges, line by line, in cents.
const AMOUNTS: [[i64; 3]; 3] = [
    [125_000, 9_600, 21_025],
    [48_050, 4_800, 21_025],
    [312_400, 15_200, 42_050],
];

/// The sheets each statement claims: the first, and the one after the last.
///
/// The first statement runs to two sheets, its terms following it; the other
/// two are a sheet each.
const RUNS: [(usize, usize); 3] = [(0, 2), (2, 3), (3, 4)];

/// An amount, with a space between its thousands and a point before its cents.
fn money(cents: i64) -> String {
    let (whole, fraction) = (cents / 100, cents % 100);
    let digits = whole.to_string();
    let mut out = String::with_capacity(digits.len() + 8);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            out.push('\u{00A0}');
        }
        out.push(digit);
    }
    format!("{out}.{fraction:02}\u{00A0}EUR")
}

/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
    c: &mut Content,
    handle: &FontHandle,
    size: f64,
    top: f64,
    text: &str,
) -> Result<f64, Error> {
    let flow = TextFlow::new(handle, size);
    let lines = flow.break_lines(text, WIDTH);
    c.begin_text();
    flow.draw(c, &lines, LEFT, top, WIDTH)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// The lines and total of one statement.
fn charges<'f>(words: &Words, text: &'f FontHandle, index: usize) -> Result<Table<'f>, Error> {
    let columns = Columns::new(
        vec![ColumnWidth::Fraction(1.0), ColumnWidth::Points(110.0)],
        WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.header(1);
    table
        .rule(Rule::Frame, Stroke::black(0.75))
        .rule(Rule::HorizontalOther, Stroke::new(0.5, Rgb::gray(0.6)))
        .rule(Rule::Vertical(1), Stroke::new(0.5, Rgb::gray(0.6)));

    let pad = Padding::symmetric(5.0, 4.0);
    let heading = |label: &str, align| {
        Cell::new(text, 9.5, label)
            .padding(pad)
            .align(align)
            .fill(Rgb::new(0.93, 0.94, 0.97))
    };
    table.push(
        Row::new()
            .cell(heading(words.columns[0], Align::Left))
            .cell(heading(words.columns[1], Align::Right))
            .min_height(19.0),
    );

    for (label, amount) in words.lines.iter().zip(AMOUNTS[index]) {
        table.push(
            Row::new()
                .cell(Cell::new(text, 9.0, *label).padding(pad))
                .cell(
                    Cell::new(text, 9.0, money(amount))
                        .padding(pad)
                        .align(Align::Right),
                )
                .min_height(16.0),
        );
    }

    table.push(
        Row::new()
            .cell(Cell::new(text, 9.5, words.total).padding(pad))
            .cell(
                Cell::new(text, 9.5, money(AMOUNTS[index].iter().sum()))
                    .padding(pad)
                    .align(Align::Right),
            )
            .min_height(19.0),
    );
    Ok(table)
}

/// Draws the foot of a sheet: who it is for, and where it stands in its
/// statement.
fn foot(
    c: &mut Content,
    words: &Words,
    text: &FontHandle,
    index: usize,
    sheet: usize,
) -> Result<(), Error> {
    let (first, after) = RUNS[index];
    let flow = TextFlow::new(text, 8.0);
    let line = format!(
        "{} {}/{} \u{2014} {} \u{2014} {} {}/{}",
        words.statement,
        index + 1,
        RUNS.len(),
        words.recipients[index],
        words.sheet,
        sheet + 1,
        after - first
    );
    c.set_fill(Rgb::gray(0.45))?;
    c.begin_text();
    flow.draw(c, &flow.break_lines(&line, WIDTH), LEFT, 56.0, WIDTH)?;
    c.end_text();
    c.set_fill(Rgb::gray(0.0))?;
    Ok(())
}

/// Draws the sheet a statement is charged on.
fn charge_sheet(words: &Words, text: &FontHandle, index: usize) -> Result<Vec<u8>, Error> {
    let mut c = Content::new();
    let mut top = 782.0;

    if index == 0 {
        top = block(&mut c, text, 17.0, top, words.title)? - 12.0;
        top = block(&mut c, text, 9.5, top, words.lead)? - 26.0;
    }

    top = block(&mut c, text, 13.0, top, words.recipients[index])? - 6.0;
    let whereabouts = format!(
        "{} {} \u{2014} {}, {}",
        words.customer, NUMBERS[index], words.towns[index], words.country
    );
    top = block(&mut c, text, 9.0, top, &whereabouts)? - 20.0;

    let placed = charges(words, text, index)?.fit(LEFT, top, 120.0, 0)?;
    placed.draw(&mut c)?;

    if index == 0 {
        c.set_fill(Rgb::gray(0.35))?;
        block(&mut c, text, 8.5, placed.bottom() - 26.0, words.note)?;
        c.set_fill(Rgb::gray(0.0))?;
    }

    foot(&mut c, words, text, index, 0)?;
    Ok(c.into_bytes())
}

/// Draws the terms sheet that follows the first statement.
fn terms_sheet(words: &Words, text: &FontHandle) -> Result<Vec<u8>, Error> {
    let mut c = Content::new();
    let top = block(&mut c, text, 13.0, 782.0, words.terms_title)? - 14.0;
    block(&mut c, text, 9.5, top, words.terms)?;
    foot(&mut c, words, text, 0, 1)?;
    Ok(c.into_bytes())
}

/// The data file carried beside one statement.
fn carried(words: &Words, index: usize) -> Attachment {
    let total: i64 = AMOUNTS[index].iter().sum();
    Attachment {
        file_name: format!("statement-{}.xml", NUMBERS[index]),
        description: words.carried.to_owned(),
        media_type: "text/xml".to_owned(),
        relationship: Relationship::Data,
        modified: POSTED[index].to_owned(),
        data: format!(
            "<statement customer=\"{}\" total=\"{total}\"/>\n",
            NUMBERS[index]
        )
        .into_bytes(),
    }
}

/// What one statement states about itself, for whatever prints it.
fn stated(words: &Words, index: usize) -> Result<PartData, Error> {
    let address = PartData::new()
        .set("Town", words.towns[index])?
        .set("Country", words.country)?;
    PartData::new()
        .set("Recipient", words.recipients[index])?
        .set("CustomerNumber", NUMBERS[index])?
        .set("Copies", COPIES[index])?
        .set("Posted", PartValue::date(POSTED[index]))?
        .set("Address", address)
}

/// The hierarchy: one part per statement, under the part that is the whole run.
fn hierarchy(words: &Words, files: [AttachmentHandle; 3]) -> Result<DocumentParts, Error> {
    let mut run = DocumentPart::new();
    for (index, file) in files.into_iter().enumerate() {
        let (first, after) = RUNS[index];
        run = run.child(
            DocumentPart::new()
                .pages(first..after)
                .data(stated(words, index)?)
                .associated_files(vec![file]),
        );
    }
    DocumentParts::new(run)
        .node_names(["Run", "Statement"])
        .map(|parts| parts.record_level(1))
}

/// Draws the four sheets and says which of them belong to which statement.
fn build(words: &Words, font: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    // The hierarchy of document parts is written on PDF 2.0 and on nothing
    // earlier.
    doc.set_version(Version::V2_0);
    let text = doc.add_font(Font::parse(fs::read(font)?)?);

    let files = [
        doc.attach(carried(words, 0)),
        doc.attach(carried(words, 1)),
        doc.attach(carried(words, 2)),
    ];

    let mut first = Page::a4();
    first.content = charge_sheet(words, &text, 0)?;
    doc.add_page(first)?;

    let mut second = Page::a4();
    second.content = terms_sheet(words, &text)?;
    doc.add_page(second)?;

    for index in 1..3 {
        let mut sheet = Page::a4();
        sheet.content = charge_sheet(words, &text, index)?;
        doc.add_page(sheet)?;
    }

    doc.set_document_parts(hierarchy(words, files)?);
    Ok(doc.to_bytes()?)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("document_parts")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let bytes = build(words, &font_path)?;

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!("wrote {out}: {} bytes", bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Font, FontHandle};

    use super::{AMOUNTS, COPIES, NUMBERS, RUNS, WIDTH, WORDS, default_font, language, money};

    /// The font the pages are set in, to measure what they draw.
    fn handle() -> FontHandle {
        let mut doc = hqf_pdf::Document::new();
        doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the test font")).expect("a font"),
        )
    }

    /// The lines two languages are allowed to write the same way: the label on
    /// the total row is the same word in English and in French.
    const SPARED: [&str; 1] = ["total: \"Total\""];

    #[test]
    fn every_language_draws_the_pages_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the pages say these in more than one language: {untranslated:?}"
        );
    }

    #[test]
    fn the_statements_claim_every_sheet_of_the_run_exactly_once() {
        let sheets = RUNS.last().expect("three statements").1;
        let mut claims = vec![0_usize; sheets];
        for (first, after) in RUNS {
            assert!(first < after, "a statement claims no sheet at all");
            for claimed in claims.iter_mut().take(after).skip(first) {
                *claimed += 1;
            }
        }

        assert!(
            claims.iter().all(|&count| count == 1),
            "the sheets are claimed {claims:?} times"
        );
    }

    #[test]
    fn every_statement_has_a_customer_a_number_of_copies_and_a_run_of_sheets() {
        for (_, words) in &WORDS {
            assert_eq!(words.recipients.len(), RUNS.len());
            assert_eq!(words.towns.len(), RUNS.len());
        }
        assert_eq!(NUMBERS.len(), RUNS.len());
        assert_eq!(COPIES.len(), RUNS.len());
        assert_eq!(AMOUNTS.len(), RUNS.len());
    }

    #[test]
    fn every_line_of_a_statement_fits_the_column_it_is_set_in() {
        let font = handle();
        // The right column is 110 points wide and every cell is padded by five
        // points on each side.
        let labels = WIDTH - 110.0 - 10.0;
        for (_, words) in &WORDS {
            for label in words.lines {
                assert!(
                    font.measure(label, 9.0) <= labels,
                    "{label:?} needs {} of {labels}",
                    font.measure(label, 9.0)
                );
            }
            assert!(
                font.measure(words.columns[1], 9.5) <= 100.0,
                "{:?} needs {} of 100",
                words.columns[1],
                font.measure(words.columns[1], 9.5)
            );
        }
    }

    #[test]
    fn the_largest_amount_a_statement_draws_fits_its_column() {
        let font = handle();
        let largest = AMOUNTS
            .iter()
            .map(|lines| lines.iter().sum::<i64>())
            .max()
            .expect("three statements");

        assert!(
            font.measure(&money(largest), 9.5) <= 100.0,
            "{} needs {}",
            money(largest),
            font.measure(&money(largest), 9.5)
        );
    }

    #[test]
    fn an_amount_is_written_with_a_space_between_its_thousands() {
        assert_eq!(money(9_600), "96.00\u{00A0}EUR");
        assert_eq!(money(48_050), "480.50\u{00A0}EUR");
        assert_eq!(money(125_000), "1\u{00A0}250.00\u{00A0}EUR");
        assert_eq!(
            money(AMOUNTS[2].iter().sum()),
            "3\u{00A0}696.50\u{00A0}EUR",
            "the largest total the pages draw"
        );
    }
}