Une table des matières à points de conduite

Une table des matières dont les entrées sont menées à leurs numéros de page par des points que la mise en page trace.

Rust write_contents.rs 220 lignes
  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
//! A contents page: every entry led to its page number by a row of dots.
//!
//! The dots are not written into the text. Each entry is a cell that asks for a
//! leader, and the layout fills whatever room the entry leaves — which is why
//! the dots still meet the numbers when an entry is edited, translated or set
//! in another font.
//!
//! Usage: `cargo run --example write_contents -- tmp/contents.pdf [font.ttf]`

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::{Align, Document, Font, FontHandle, Page, Rgb, TextFlow};

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

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

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

/// A4's width, and the margins the contents are laid out between.
const PAGE_WIDTH: f64 = 595.276;
const MARGIN: f64 = 64.0;
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * MARGIN;

/// One line of the contents: how deep it sits, what it says, and the page it
/// sends the reader to.
struct Entry {
    depth: usize,
    label: &'static str,
    page: &'static str,
}

/// The contents of the report this page opens.
const ENTRIES: &[Entry] = &[
    Entry {
        depth: 0,
        label: "1  Scope of the audit",
        page: "3",
    },
    Entry {
        depth: 1,
        label: "1.1  What was examined",
        page: "3",
    },
    Entry {
        depth: 1,
        label: "1.2  What was left out, and why",
        page: "5",
    },
    Entry {
        depth: 0,
        label: "2  How the documents are produced today",
        page: "8",
    },
    Entry {
        depth: 1,
        label: "2.1  The invoicing run",
        page: "8",
    },
    Entry {
        depth: 1,
        label: "2.2  The nightly statement of accounts",
        page: "11",
    },
    Entry {
        depth: 1,
        label: "2.3  Documents produced on demand from the counter",
        page: "14",
    },
    Entry {
        depth: 0,
        label: "3  What the archival standard asks for",
        page: "17",
    },
    Entry {
        depth: 1,
        label: "3.1  Fonts that travel with the file",
        page: "17",
    },
    Entry {
        depth: 1,
        label: "3.2  Colour that means the same on every screen",
        page: "20",
    },
    Entry {
        depth: 1,
        label: "3.3  Text a reading machine can follow",
        page: "23",
    },
    Entry {
        depth: 0,
        label: "4  What it would cost to change",
        page: "27",
    },
    Entry {
        depth: 1,
        label: "4.1  The work, month by month",
        page: "27",
    },
    Entry {
        depth: 1,
        label: "4.2  What is saved once it is done",
        page: "31",
    },
    Entry {
        depth: 0,
        label: "Appendix  Files read for this report",
        page: "34",
    },
];

/// How far a sub-entry is set in from the margin, in points.
const INDENT: f64 = 18.0;

/// The contents, as one table: the entry, led by dots to its page number.
fn contents(font: &FontHandle) -> Result<Table<'_>, hqf_pdf::Error> {
    let columns = Columns::new(
        vec![ColumnWidth::Fraction(1.0), ColumnWidth::Points(28.0)],
        TABLE_WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.rule(Rule::Horizontal(0), Stroke::new(0.5, Rgb::gray(0.7)));

    for entry in ENTRIES {
        let top = entry.depth == 0;
        let size = if top { 10.5 } else { 9.5 };
        let color = if top { Rgb::BLACK } else { Rgb::gray(0.25) };
        let padding = Padding {
            left: INDENT * count(entry.depth),
            right: 4.0,
            top: if top { 7.0 } else { 2.0 },
            bottom: 2.0,
        };

        table.push(
            Row::new()
                .cell(
                    Cell::new(font, size, entry.label)
                        .color(color)
                        .padding(padding)
                        // The dots are drawn by the layout, in the room the
                        // entry leaves.
                        .leader('.'),
                )
                .cell(
                    Cell::new(font, size, entry.page)
                        .color(color)
                        .align(Align::Right)
                        .padding(padding),
                ),
        );
    }

    Ok(table)
}

/// Converts a nesting depth to a float. A contents page never nests deep enough
/// for a `usize` to lose precision as an `f64`.
#[expect(
    clippy::cast_precision_loss,
    reason = "a nesting depth is far below f64's exact-integer range"
)]
const fn count(n: usize) -> f64 {
    n as f64
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = env::args().skip(1);
    let out = args.next().unwrap_or_else(|| out::default_path("contents"));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

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

    let mut c = Content::new();

    let title = TextFlow::new(&font, 20.0);
    let title_lines = title.break_lines("Contents", TABLE_WIDTH);
    c.begin_text();
    title.draw(&mut c, &title_lines, MARGIN, 790.0, TABLE_WIDTH)?;
    c.end_text();

    let subtitle = TextFlow::new(&font, 8.5).color(Rgb::gray(0.4));
    let subtitle_lines = subtitle.break_lines(
        "Audit of document production — ACME Ltd, second quarter",
        TABLE_WIDTH,
    );
    c.begin_text();
    subtitle.draw(&mut c, &subtitle_lines, MARGIN, 762.0, TABLE_WIDTH)?;
    c.end_text();

    let table = contents(&font)?;
    table.fit(MARGIN, 730.0, 660.0, 0)?.draw(&mut c)?;

    let mut page = Page::a4();
    page.content = c.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", bytes.len());
    Ok(())
}