write_portfolio.rs

Le fichier Rust de l'exemple « Un dossier d'appel d'offres de trois lots ». Trois lots, chacun voyageant comme un fichier à part, sous les colonnes que le document lui-même énonce — lot, jour d'envoi, montant —, triés sur le jour, du plus récent au plus ancien. La feuille de garde dispose les mêmes colonnes pour un logiciel de lecture qui ne montre pas de dossier.

Rust 332 lignes

À quoi sert cet exemple

Trois entreprises répondent à un appel d'offres, et ce qui arrive, ce sont trois jeux de chiffres qui doivent rester distincts et voyager ensemble. Chaque lot entre dans ce document comme un fichier à part, entier, dans la forme où il a été envoyé. Ce qui transforme cela en un dossier qu'on peut dépouiller, c'est le reste : le document nomme les colonnes sous lesquelles les fichiers sont présentés — le lot, le jour de l'envoi, le montant —, dit ce que chaque fichier met dans chacune, et dit que la liste est triée sur le jour, du plus récent au plus ancien.

Ce que montre cet exemple

  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
//! Writes a tender pack: a cover sheet, three files attached to it, and the
//! table a reading software shows them in.
//!
//! A document that carries files is a portfolio when it says how to show them:
//! which columns to lay out, what each file states for each column, and which
//! way the list is sorted. Without that a reading software falls back on a list
//! of file names, which tells a buyer nothing about which lot came in when and
//! for how much.
//!
//! Each lot is attached as a small XML file, and each states its own lot, the
//! day it was sent and its total. The columns are declared once on the
//! document, the sort is on the day, newest first, and the cover sheet lists
//! the files as well, so that a reading software with no portfolio of its own
//! still shows what is inside.
//!
//! The dates the columns carry are written the way PDF writes a moment, which
//! is what `metadata::date::to_pdf` turns an ISO 8601 moment into. A file's own
//! `modified` is stated in ISO 8601 and converted by the library.
//!
//! Usage: `cargo run --example write_portfolio -- tmp/portfolio.pdf`
//!        `HQF_PDF_LANG=fr cargo run --example write_portfolio -- tmp/lots.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::TextFlow;
use hqf_pdf::metadata::attachment::{Attachment, Relationship};
use hqf_pdf::metadata::date;
use hqf_pdf::{
    Collection, CollectionData, CollectionField, CollectionValue, CollectionView, Document, Font,
    FontHandle, Page, Rgb,
};

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

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

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

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

use language::Language;

/// The font the example draws with.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The margin the page is laid out inside.
const MARGIN: f64 = 56.0;

/// How far the page runs across, between the margins.
const WIDTH: f64 = 483.0;

/// How many lots the pack carries.
const LOTS: usize = 3;

/// The name each lot is attached under.
const FILES: [&str; LOTS] = ["lot-a.xml", "lot-b.xml", "lot-c.xml"];

/// When each lot was sent, in ISO 8601.
const SENT: [&str; LOTS] = [
    "2026-07-14T09:30:00+02:00",
    "2026-08-03T16:05:00+02:00",
    "2026-06-28T11:20:00+02:00",
];

/// What each lot comes to, in euros.
const TOTALS: [f64; LOTS] = [18_400.0, 9_250.0, 31_700.0];

/// Where each line of the list sits.
const ROWS: [f64; LOTS] = [648.0, 626.0, 604.0];

/// Where the heading of the list sits.
const HEADING: f64 = 676.0;

/// Where each column of the list starts, from the margin.
const COLUMNS: [f64; 4] = [0.0, 96.0, 300.0, 392.0];

/// The keys the columns are read under. They are not words anybody is shown: a
/// file states its columns under these, and the sort names one of them.
const KEYS: [&str; LOTS] = ["lot", "sent", "total"];

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The paragraph under it.
    intro: &'static str,
    /// The heading each column is shown under.
    columns: [&'static str; LOTS],
    /// What each lot is called.
    lots: [&'static str; LOTS],
    /// What each lot comes to, written the way the language writes money.
    totals: [&'static str; LOTS],
    /// The heading over the column of file names.
    file_heading: &'static str,
    /// The line under the list.
    caption: &'static str,
}

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

/// The page in English.
const ENGLISH: Words = Words {
    title: "Tender pack: three lots",
    intro: "Every lot of this tender travels in the pack as a file of its own. \
            The document states the columns the files are shown in, what each \
            file holds for each of them, and that the list is sorted on the day \
            it was sent, newest first.",
    columns: ["Lot", "Sent", "Total"],
    lots: [
        "Earthworks and site clearance",
        "Drainage and services",
        "Surfacing and lining",
    ],
    totals: ["EUR 18,400.00", "EUR 9,250.00", "EUR 31,700.00"],
    file_heading: "File",
    caption: "A reading software that shows a portfolio lays the three files out \
              in these columns. One that does not still opens the pack and \
              lists the files, which is why they are named on this sheet too.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Dossier d'appel d'offres : trois lots",
    intro: "Chaque lot de cet appel d'offres voyage dans le dossier comme un \
            fichier à part. Le document dit les colonnes sous lesquelles les \
            fichiers sont présentés, ce que chacun y porte, et que la liste est \
            triée sur le jour de l'envoi, du plus récent au plus ancien.",
    columns: ["Lot", "Envoyé", "Montant"],
    lots: [
        "Terrassement et dégagement du terrain",
        "Drainage et réseaux",
        "Revêtement et marquage",
    ],
    totals: ["18 400,00 EUR", "9 250,00 EUR", "31 700,00 EUR"],
    file_heading: "Fichier",
    caption: "Un logiciel de lecture qui présente un portefeuille dispose les \
              trois fichiers sous ces colonnes. Celui qui ne le fait pas ouvre \
              tout de même le dossier et liste les fichiers : c'est pourquoi \
              ils sont aussi nommés sur cette feuille.",
};

/// 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 day of an ISO 8601 moment, which is what the list shows.
fn day_of(moment: &str) -> &str {
    moment.split('T').next().unwrap_or(moment)
}

/// The file one lot is sent as.
fn lot_file(name: &str, sent: &str, total: f64) -> Vec<u8> {
    format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <lot>\n  <name>{name}</name>\n  <sent>{sent}</sent>\n  \
         <total currency=\"EUR\">{total:.2}</total>\n</lot>\n"
    )
    .into_bytes()
}

/// Writes a line of ordinary text at `(x, y)`.
fn write(
    content: &mut Content,
    font: &FontHandle,
    x: f64,
    y: f64,
    size: f64,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(text));
    content.end_text();
    Ok(())
}

/// Writes a paragraph in a column the width of the page.
fn paragraph(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    top: f64,
    color: Rgb,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    let flow = TextFlow::new(font, size).leading(size * 1.4).color(color);
    let lines = flow.break_lines(text, WIDTH);
    content.begin_text();
    flow.draw(content, &lines, MARGIN, top, WIDTH)?;
    content.end_text();
    Ok(())
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

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

    // 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 = env::args()
        .nth(1)
        .unwrap_or_else(|| language.file_name(&out::default_path("portfolio")));

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(default_font())?)?);

    for lot in 0..LOTS {
        doc.attach(
            Attachment::new(
                FILES[lot],
                words.lots[lot],
                "application/xml",
                Relationship::Source,
                SENT[lot],
                lot_file(words.lots[lot], SENT[lot], TOTALS[lot]),
            )
            .stating(KEYS[0], CollectionValue::Text(words.lots[lot].to_owned()))
            .stating(KEYS[1], CollectionValue::Date(date::to_pdf(SENT[lot])?))
            .stating(KEYS[2], CollectionValue::Number(TOTALS[lot])),
        );
    }

    doc.set_collection(
        Collection::new(CollectionView::Rows)
            .with_columns(vec![
                CollectionField::new(KEYS[0], words.columns[0], CollectionData::Text),
                CollectionField::new(KEYS[1], words.columns[1], CollectionData::Date),
                CollectionField::new(KEYS[2], words.columns[2], CollectionData::Number),
            ])
            .sorted_by(KEYS[1], false),
    );

    let mut content = Content::new();
    write(&mut content, &font, MARGIN, 780.0, 16.0, words.title)?;
    paragraph(&mut content, &font, 10.0, 750.0, Rgb::BLACK, words.intro)?;

    let headings = [
        words.file_heading,
        words.columns[0],
        words.columns[1],
        words.columns[2],
    ];
    for (column, heading) in COLUMNS.iter().zip(headings) {
        write(&mut content, &font, MARGIN + *column, HEADING, 9.0, heading)?;
    }
    content.save_state();
    content.set_stroke(Rgb::gray(0.75))?;
    content.set_line_width(0.5)?;
    content.move_to(MARGIN, HEADING - 6.0)?;
    content.line_to(MARGIN + WIDTH, HEADING - 6.0)?;
    content.stroke();
    content.restore_state();

    for (lot, at) in ROWS.iter().enumerate() {
        let cells = [
            FILES[lot],
            words.lots[lot],
            day_of(SENT[lot]),
            words.totals[lot],
        ];
        for (column, cell) in COLUMNS.iter().zip(cells) {
            write(&mut content, &font, MARGIN + *column, *at, 10.0, cell)?;
        }
    }

    paragraph(
        &mut content,
        &font,
        8.5,
        566.0,
        Rgb::gray(0.35),
        words.caption,
    )?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;

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

#[cfg(test)]
mod tests {
    use super::{WORDS, language};

    /// The lines two languages write the same way: a lot is a lot in both.
    const SPARED: [&str; 1] = [r#""Lot""#];

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

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