write_imported_pages.rs

Die Rust-Datei des Beispiels „Ein Vertrag auf drei mitgelieferten Vorlagen“. Ein Liefervertrag auf drei Vorlagen, die der Kunde geschickt hat: eine Seite mit Briefkopf unter der ersten Seite, eine leere Seite unter jeder Seite, über die der Lieferplan läuft, und eine Bedingungsseite, die vollständig hineinkommt.

Rust 1662 Zeilen

Wofür dieses Beispiel da ist

Ein Kunde schickt sein eigenes Briefpapier als drei PDF-Dateien — die Seite mit Name und Anschrift oben, eine leere Seite für die Folgeseiten und die Seite mit den Bedingungen, die er immer ans Ende anhängt. Eine so verwendete Datei heißt Vorlage. Zurück möchte er einen Liefervertrag, der aussieht, als käme er aus seinem eigenen Drucker, und der sicherste Weg, daran zu scheitern, ist der Versuch, irgendetwas davon nachzuzeichnen.

Was dieses Beispiel zeigt

   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
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
//! Assembles a document onto three PDFs somebody else made: one behind its
//! first page, one behind every page in the middle, and one that goes in whole
//! as its last page.
//!
//! This is what a document server is asked for most often. The customer sends
//! stationery — a headed sheet, a plain continuation sheet, a page of standing
//! conditions — and the document has to be laid on it without any of it being
//! redrawn. Each sheet is read, brought in as a form, and stamped under what
//! this example draws. The conditions sheet carries nothing of its own but the
//! page number, and is a counted page like the rest.
//!
//! A field a sheet comes with is laid down again where the sheet shows it: the
//! box the conditions are accepted by is drawn by the sheet, and still ticks on
//! the pack's last page. So is every other annotation: the frame the sheet puts
//! round that box comes onto the last page with the appearance the sheet gave
//! it.
//!
//! The page the schedule needs is decided by the schedule: the table is handed
//! over whole and says how many pages it takes, so the continuation sheet backs
//! as many pages as there turn out to be.
//!
//! What the pack says is written in the language `HQF_PDF_LANG` names. What it
//! is about is not: the reference, the two parties, their addresses and their
//! tax numbers, the quantities and the prices are the same pack whichever
//! language reads it.
//!
//! The headed sheet's band sits on a layer, which comes into the pack's own
//! panel with the page. Each sheet is stamped from the starting graphics state,
//! and the conditions sheet is taken as the part of it a reader is shown.
//!
//! The three sheets may be handed over on the command line. With none given,
//! the example writes them itself, so it runs on any machine.
//!
//! Usage: `cargo run --example write_imported_pages -- tmp/pack.pdf [headed.pdf
//! continuation.pdf conditions.pdf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_imported_pages`

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

use hqf_pdf::annotation::{Annotation, Square};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{
    Area, Cell, ColumnWidth, Columns, Margin, Padding, Row, Rule, Stroke, Table, TableFrame, VAlign,
};
use hqf_pdf::read::{FieldKind, ImportedPage, PageBoundary, PageImport, Reader};
use hqf_pdf::{Align, CheckBox, Document, ExtGState, Field, Font, FontHandle, Layer, 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 every sheet and the pack itself are drawn with.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// A4, in points.
const PAGE_WIDTH: f64 = 595.276;
/// The page's left edge and, mirrored, its right.
const LEFT: f64 = 56.0;
const RIGHT: f64 = PAGE_WIDTH - LEFT;
/// The width the table is fitted across.
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * LEFT;
/// Where the second column of the two address blocks begins.
const SECOND_COLUMN: f64 = 320.0;

/// The ink the headings and rules are drawn in, and the grey of the small
/// print.
const ACCENT: Rgb = Rgb {
    r: 0.11,
    g: 0.33,
    b: 0.55,
};
const MUTED: Rgb = Rgb {
    r: 0.42,
    g: 0.42,
    b: 0.45,
};
const INK: Rgb = Rgb {
    r: 0.1,
    g: 0.1,
    b: 0.12,
};

/// The agreement this pack schedules, which no language renumbers.
const REFERENCE: &str = "SA-2027-0088";

/// The supplier and the customer: what they are called, where they are, and the
/// tax number each answers to. None of it is language.
const SUPPLIER: &str = "HQF Development";
const SUPPLIER_STREET: &str = "42 lot les Genêts";
const SUPPLIER_TOWN: &str = "13480 Calas, France";
const SUPPLIER_VAT: &str = "FR59 752 492 777";
const CUSTOMER: &str = "Meridian Optics SAS";
const CUSTOMER_STREET: &str = "18 avenue des Peupliers";
const CUSTOMER_TOWN: &str = "69100 Villeurbanne, France";
const CUSTOMER_VAT: &str = "FR41 512 336 908";

/// The box the conditions are accepted by, on the conditions sheet: its
/// lower-left corner and its side.
const ACCEPTED_BOX: (f64, f64, f64) = (LEFT, 126.0, 10.0);

/// The size a field a sheet comes with sets its text in, where it holds any.
const FIELD_SIZE: f64 = 9.0;

/// The box the schedule is fitted into, on whichever page it lands.
const TABLE_TOP: f64 = 780.0;
const TABLE_BOTTOM: f64 = 80.0;

/// What the pack says, in one language.
///
/// What it is about is held outside: the reference, the parties, their
/// addresses, their tax numbers, the days, the quantities and the prices are
/// the same pack in every language.
#[derive(Debug)]
struct Words {
    /// What the pack is called, at the head of its front page.
    title: &'static str,
    /// What stands between the reference and the day the pack was drawn up.
    drawn_up: &'static str,
    /// The day it was drawn up.
    drawn_up_on: &'static str,
    /// What heads each of the two address blocks.
    supplier: &'static str,
    customer: &'static str,
    /// What stands before a tax number.
    vat: &'static str,
    /// The name of the layer the headed sheet's band sits on.
    letterhead: &'static str,
    /// What heads the lines that say what the pack stands on.
    made_of: &'static str,
    /// Those lines, broken where the page breaks them: what the pack stands on,
    /// then what is done with it.
    stands_on: [&'static str; 3],
    /// What is done with it.
    stamped: [&'static str; 3],
    /// What heads the list of the pack's own pages.
    in_it: &'static str,
    /// What one page of the pack is called, and what several are.
    page: &'static str,
    pages: &'static str,
    /// What runs between the first page of a span and its last.
    to: &'static str,
    /// What runs between a page's number and how many there are.
    of: &'static str,
    /// What each of the three entries of the list says.
    front_sheet: &'static str,
    schedule_before: &'static str,
    schedule_after: &'static str,
    conditions_entry: &'static str,
    /// What heads the two places the parties sign, and the line under it.
    signed: &'static str,
    signed_note: &'static str,
    /// What stands before the name of a party over the rule it signs on.
    for_party: &'static str,
    /// What is asked for under the second rule.
    name_and_date: &'static str,
    /// The four headings of the schedule.
    headings: [&'static str; 4],
    /// What each batch delivers, in the order [`BATCHES`] schedules them.
    batches: [&'static str; 11],
    /// The month each quarter's batches are due in, in the order [`YEARS`] runs
    /// them.
    months: [&'static str; 4],
    /// What the last row of the schedule adds up.
    total: &'static str,
    /// What the conditions sheet is headed, and the line at its foot.
    conditions_title: &'static str,
    conditions_edition: &'static str,
    /// What stands beside the box the conditions are accepted by.
    accepted: &'static str,
    /// The standing clauses, one to a line.
    clauses: [&'static str; 16],
}

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

/// The pack in English.
const ENGLISH: Words = Words {
    title: "Supply agreement",
    drawn_up: "drawn up",
    drawn_up_on: "12 March 2027",
    supplier: "Supplier",
    customer: "Customer",
    vat: "VAT",
    letterhead: "Letterhead",
    made_of: "What this pack is made of",
    stands_on: [
        "This pack stands on three sheets the customer sent as PDF files. The headed sheet is under",
        "this page. A plain continuation sheet is under every page the schedule runs to. The page of",
        "standing conditions at the back is the third sheet, taken in whole and counted like the rest.",
    ],
    stamped: [
        "None of the three is redrawn. The team reads each file, brings its page in as a drawing, and",
        "stamps it under the text — so a letterhead comes out of the printer as its owner made it, and",
        "the conditions on the last page are the ones on file, to the letter.",
    ],
    in_it: "What is in it",
    page: "Page",
    pages: "Pages",
    to: "to",
    of: "of",
    front_sheet: "This page, on the headed sheet.",
    schedule_before: "The delivery schedule, ",
    schedule_after: " rows, on the continuation sheet.",
    conditions_entry: "The conditions of supply, as the customer supplied them.",
    signed: "Signed",
    signed_note: "Each party signs one copy. The schedule and the conditions of supply are part of it.",
    for_party: "For",
    name_and_date: "Name and date",
    headings: ["Batch", "Due", "Quantity", "Value"],
    batches: [
        "Lens blanks, 62 mm, coated",
        "Lens blanks, 68 mm, coated",
        "Lens blanks, 74 mm, uncoated",
        "Frame fronts, acetate, assorted",
        "Frame temples, acetate, pairs",
        "Hinges, sprung, stainless",
        "Nose pads, silicone",
        "Screws, M1.4, boxed by hundred",
        "Cases, hard, printed",
        "Cloths, microfibre, printed",
        "Cartons, shipping, printed",
    ],
    months: ["April", "July", "October", "January"],
    total: "Total, before tax",
    conditions_title: "Conditions of supply",
    conditions_edition: "conditions of supply, edition of 1 January 2027",
    accepted: "Read and accepted",
    clauses: [
        "Prices are firm for the term of this agreement, in euros, exclusive of value added tax.",
        "A batch is due on the day named in the schedule, at the address the schedule was sent to.",
        "Quantities are counted on arrival. A count that differs is settled within five working days.",
        "Payment falls thirty days after the batch arrives, by transfer to the account on the invoice.",
        "Title to a batch passes on payment. Risk passes on arrival.",
        "A batch refused on arrival is collected within ten working days, at the supplier's cost.",
        "Either party may end this agreement on ninety days' notice, in writing.",
        "Batches already scheduled at the end of the notice are supplied and paid for as scheduled.",
        "Neither party is answerable for a delay caused by an event outside its reasonable control.",
        "This agreement is governed by French law, and the courts of Aix-en-Provence hear disputes.",
        "A change to a scheduled batch takes effect only when both parties agree it in writing.",
        "The supplier keeps a certificate of conformity for each batch three years after it arrives.",
        "The customer's marks may go on cartons and cases for the term, and to no other purpose.",
        "Neither party may hand this agreement to anyone else without the other's written consent.",
        "Notices are given in writing, to the addresses printed on the first page of this pack.",
        "This pack, its schedule and these conditions are the whole of what the parties agreed.",
    ],
};

/// The pack in French.
const FRENCH: Words = Words {
    title: "Contrat d’approvisionnement",
    drawn_up: "établi le",
    drawn_up_on: "12 mars 2027",
    supplier: "Fournisseur",
    customer: "Client",
    vat: "TVA",
    letterhead: "Papier à en-tête",
    made_of: "Composition du dossier",
    stands_on: [
        "Ce dossier s’appuie sur trois feuilles que le client a envoyées en PDF. La \
feuille à en-tête se",
        "trouve sous cette page ; une feuille de suite vierge, sous chaque page du \
calendrier. La page des",
        "conditions de fourniture, à la fin, est la troisième, reprise entière et \
comptée comme les autres.",
    ],
    stamped: [
        "Aucune des trois n’est refaite. L’équipe lit chaque fichier, en reprend la page comme un",
        "dessin et l’appose sous le texte : un papier à en-tête sort ainsi de l’imprimante tel que",
        "son propriétaire l’a conçu ; la dernière page reprend les conditions du \
fichier, à la lettre.",
    ],
    in_it: "Contenu du dossier",
    page: "Page",
    pages: "Pages",
    to: "à",
    of: "sur",
    front_sheet: "Cette page, sur la feuille à en-tête.",
    schedule_before: "Le calendrier de livraison, ",
    schedule_after: " lignes, sur la feuille de suite.",
    conditions_entry: "Les conditions de fourniture, telles que le client les a transmises.",
    signed: "Signatures",
    signed_note: "Chaque partie signe un exemplaire. Le calendrier et les conditions de \
fourniture font partie du contrat.",
    for_party: "Pour",
    name_and_date: "Nom et date",
    headings: ["Lot", "Échéance", "Quantité", "Montant"],
    batches: [
        "Ébauches de verres, 62 mm, traitées",
        "Ébauches de verres, 68 mm, traitées",
        "Ébauches de verres, 74 mm, non traitées",
        "Faces de monture, acétate, assorties",
        "Branches de monture, acétate, paires",
        "Charnières à ressort, inox",
        "Plaquettes nasales, silicone",
        "Vis M1.4, boîtes de cent",
        "Étuis rigides, imprimés",
        "Chiffonnettes microfibre, imprimées",
        "Cartons d’expédition, imprimés",
    ],
    months: ["avril", "juillet", "octobre", "janvier"],
    total: "Total hors taxes",
    conditions_title: "Conditions de fourniture",
    conditions_edition: "conditions de fourniture, édition du 1er janvier 2027",
    accepted: "Lu et approuvé",
    clauses: [
        "Les prix sont fermes pour la durée du contrat, en euros, hors taxe sur la valeur ajoutée.",
        "Un lot est livré le jour indiqué au calendrier, à l’adresse où celui-ci a été envoyé.",
        "Les quantités sont comptées à l’arrivée. Un écart de comptage se règle sous \
cinq jours ouvrés.",
        "Le paiement échoit trente jours après l’arrivée du lot, par virement au compte \
indiqué sur la facture.",
        "La propriété d’un lot est transférée au paiement, les risques à l’arrivée.",
        "Un lot refusé à l’arrivée est repris sous dix jours ouvrés, aux frais du fournisseur.",
        "Chaque partie peut résilier le contrat par écrit, moyennant un préavis de \
quatre-vingt-dix jours.",
        "Les lots déjà inscrits au calendrier à la fin du préavis sont livrés et payés comme prévu.",
        "Aucune partie ne répond d’un retard dû à un événement indépendant de sa volonté.",
        "Le contrat est régi par le droit français ; les tribunaux d’Aix-en-Provence \
sont compétents pour tout litige.",
        "Toute modification d’un lot prévu au calendrier ne prend effet qu’après accord \
écrit des deux parties.",
        "Le fournisseur conserve un certificat de conformité par lot pendant trois ans après son arrivée.",
        "Les marques du client peuvent figurer sur cartons et étuis pendant le contrat, \
à nulle autre fin.",
        "Aucune partie ne peut céder le contrat à un tiers sans l’accord écrit de l’autre.",
        "Les avis sont donnés par écrit, aux adresses imprimées sur la première page de ce dossier.",
        "Ce dossier, son calendrier et ces conditions constituent l’intégralité de \
l’accord des parties.",
    ],
};

/// The pack in Dutch.
const DUTCH: Words = Words {
    title: "Leveringsovereenkomst",
    drawn_up: "opgesteld op",
    drawn_up_on: "12 maart 2027",
    supplier: "Leverancier",
    customer: "Klant",
    vat: "Btw",
    letterhead: "Briefpapier",
    made_of: "Waaruit dit pakket bestaat",
    stands_on: [
        "Dit pakket is gebouwd op drie bladen die de klant als pdf-bestanden stuurde. Het briefhoofd ligt onder",
        "deze pagina. Een blanco vervolgblad ligt onder elke pagina van het schema. De pagina met",
        "algemene voorwaarden achteraan is het derde blad, geheel overgenomen en meegeteld als de rest.",
    ],
    stamped: [
        "Geen van de drie is opnieuw getekend. Het team leest elk bestand, haalt de pagina op als tekening en",
        "stempelt haar onder de tekst: zo komt een briefhoofd uit de printer zoals de eigenaar het maakte, en",
        "zijn de voorwaarden op de laatste pagina die uit het dossier, letterlijk.",
    ],
    in_it: "Wat erin zit",
    page: "Pagina",
    pages: "Pagina’s",
    to: "tot",
    of: "van",
    front_sheet: "Deze pagina, op het briefpapier.",
    schedule_before: "Het leveringsschema,",
    schedule_after: " rijen, op het vervolgblad.",
    conditions_entry: "De leveringsvoorwaarden, zoals de klant ze aanleverde.",
    signed: "Getekend",
    signed_note: "Elke partij tekent één exemplaar. Het schema en de leveringsvoorwaarden maken er deel van uit.",
    for_party: "Voor",
    name_and_date: "Naam en datum",
    headings: ["Zending", "Levering", "Aantal", "Waarde"],
    batches: [
        "Brillenglazen, 62 mm, gecoat",
        "Brillenglazen, 68 mm, gecoat",
        "Brillenglazen, 74 mm, ongecoat",
        "Montuurfronten, acetaat, gesorteerd",
        "Poten, acetaat, paren",
        "Scharnieren, veer, rvs",
        "Neuspads, siliconen",
        "Schroeven, M1,4, per honderd verpakt",
        "Etuis, hard, bedrukt",
        "Doekjes, microvezel, bedrukt",
        "Verzenddozen, bedrukt",
    ],
    months: ["April", "Juli", "Oktober", "Januari"],
    total: "Totaal, exclusief btw",
    conditions_title: "Leveringsvoorwaarden",
    conditions_edition: "leveringsvoorwaarden, uitgave van 1 januari 2027",
    accepted: "Gelezen en aanvaard",
    clauses: [
        "Prijzen staan vast voor de looptijd van deze overeenkomst, in euro, exclusief btw.",
        "Een zending wordt geleverd op de dag in het schema, op het adres waarheen het schema is gestuurd.",
        "Aantallen worden bij aankomst geteld. Een afwijkende telling wordt binnen vijf werkdagen geregeld.",
        "Betaling volgt dertig dagen na aankomst van de zending, per overschrijving naar de rekening op de factuur.",
        "De eigendom van een zending gaat over bij betaling. Het risico gaat over bij aankomst.",
        "Een bij aankomst geweigerde zending wordt binnen tien werkdagen opgehaald, op kosten van de leverancier.",
        "Elke partij kan deze overeenkomst schriftelijk opzeggen met negentig dagen opzegtermijn.",
        "Zendingen die aan het einde van de opzegtermijn al gepland zijn, worden geleverd en betaald volgens plan.",
        "Geen partij is aansprakelijk voor vertraging door een gebeurtenis buiten haar redelijke macht.",
        "Deze overeenkomst valt onder Frans recht, en de rechtbank van Aix-en-Provence beslecht geschillen.",
        "Een wijziging aan een geplande zending geldt pas als beide partijen haar schriftelijk overeenkomen.",
        "De leverancier bewaart per zending een conformiteitsverklaring tot drie jaar na aankomst.",
        "De merken van de klant mogen gedurende de looptijd alleen op dozen en etuis worden gebruikt.",
        "Geen partij mag deze overeenkomst overdragen zonder schriftelijke toestemming van de ander.",
        "Kennisgevingen worden schriftelijk gedaan, aan de adressen op de eerste pagina van dit pakket.",
        "Dit pakket, het schema en deze voorwaarden zijn alles wat de partijen zijn overeengekomen.",
    ],
};

/// The pack in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Contrato de fornecimento",
    drawn_up: "redigido em",
    drawn_up_on: "12 de março de 2027",
    supplier: "Fornecedor",
    customer: "Cliente",
    vat: "NIF",
    letterhead: "Papel timbrado",
    made_of: "De que é feito este dossiê",
    stands_on: [
        "Este dossiê assenta em três folhas que o cliente enviou em PDF. A folha timbrada está por baixo",
        "desta página. Uma folha de continuação simples está por baixo de cada página do calendário. A página",
        "de condições gerais no fim é a terceira folha, tomada inteira e contada como as outras.",
    ],
    stamped: [
        "Nenhuma das três é redesenhada. A equipa lê cada ficheiro, traz a sua página como desenho e",
        "carimba-a por baixo do texto: assim um papel timbrado sai da impressora como o dono o fez, e",
        "as condições da última página são as que estão em arquivo, à letra.",
    ],
    in_it: "O que contém",
    page: "Página",
    pages: "Páginas",
    to: "a",
    of: "de",
    front_sheet: "Esta página, na folha timbrada.",
    schedule_before: "O calendário de entregas,",
    schedule_after: " linhas, na folha de continuação.",
    conditions_entry: "As condições de fornecimento, tal como o cliente as forneceu.",
    signed: "Assinado",
    signed_note: "Cada parte assina um exemplar. O calendário e as condições de fornecimento fazem parte dele.",
    for_party: "Por",
    name_and_date: "Nome e data",
    headings: ["Lote", "Entrega", "Qtd.", "Valor"],
    batches: [
        "Lentes em bruto, 62 mm, tratadas",
        "Lentes em bruto, 68 mm, tratadas",
        "Lentes em bruto, 74 mm, sem tratamento",
        "Frentes de armação, acetato, sortidas",
        "Hastes de armação, acetato, pares",
        "Dobradiças, de mola, inox",
        "Plaquetas, silicone",
        "Parafusos, M1,4, em caixas de cem",
        "Estojos, rígidos, impressos",
        "Panos, microfibra, impressos",
        "Caixas de expedição, impressas",
    ],
    months: ["Abril", "Julho", "Outubro", "Janeiro"],
    total: "Total, sem impostos",
    conditions_title: "Condições de fornecimento",
    conditions_edition: "condições de fornecimento, edição de 1 de janeiro de 2027",
    accepted: "Lido e aceite",
    clauses: [
        "Os preços são firmes durante o contrato, em euros, sem imposto sobre o valor acrescentado.",
        "Um lote é devido no dia indicado no calendário, na morada para onde este foi enviado.",
        "As quantidades contam-se à chegada. Uma contagem diferente resolve-se em cinco dias úteis.",
        "O pagamento vence trinta dias após a chegada do lote, por transferência para a conta da fatura.",
        "A propriedade de um lote passa com o pagamento. O risco passa com a chegada.",
        "Um lote recusado à chegada é recolhido em dez dias úteis, a cargo do fornecedor.",
        "Qualquer das partes pode pôr fim a este contrato com noventa dias de pré-aviso, por escrito.",
        "Os lotes já calendarizados no fim do pré-aviso são fornecidos e pagos como previsto.",
        "Nenhuma parte responde por um atraso causado por um facto fora do seu controlo razoável.",
        "Este contrato rege-se pela lei francesa, e os litígios são submetidos aos tribunais de Aix-en-Provence.",
        "Uma alteração a um lote calendarizado só produz efeito quando ambas as partes a acordam por escrito.",
        "O fornecedor guarda um certificado de conformidade por lote durante três anos após a chegada.",
        "As marcas do cliente podem ir em caixas e estojos durante o contrato, e para nada mais.",
        "Nenhuma parte pode ceder este contrato a outrem sem o consentimento escrito da outra.",
        "As notificações fazem-se por escrito, para as moradas impressas na primeira página deste dossiê.",
        "Este dossiê, o seu calendário e estas condições são tudo o que as partes acordaram.",
    ],
};

/// The pack in Italian.
const ITALIAN: Words = Words {
    title: "Contratto di fornitura",
    drawn_up: "redatto il",
    drawn_up_on: "12 marzo 2027",
    supplier: "Fornitore",
    customer: "Cliente",
    vat: "P. IVA",
    letterhead: "Carta intestata",
    made_of: "Di cosa è fatto questo fascicolo",
    stands_on: [
        "Questo fascicolo poggia su tre fogli che il cliente ha inviato come file PDF. Il foglio intestato è sotto",
        "questa pagina. Un foglio di continuazione semplice è sotto ogni pagina del calendario. La pagina",
        "delle condizioni generali in fondo è il terzo foglio, preso per intero e contato come gli altri.",
    ],
    stamped: [
        "Nessuno dei tre è ridisegnato. Il team legge ogni file, porta la sua pagina come disegno e",
        "la stampa sotto il testo: così una carta intestata esce dalla stampante come l’ha fatta il titolare, e",
        "le condizioni dell’ultima pagina sono quelle agli atti, alla lettera.",
    ],
    in_it: "Cosa contiene",
    page: "Pagina",
    pages: "Pagine",
    to: "a",
    of: "di",
    front_sheet: "Questa pagina, sul foglio intestato.",
    schedule_before: "Il calendario di consegna,",
    schedule_after: " righe, sul foglio di continuazione.",
    conditions_entry: "Le condizioni di fornitura, come le ha fornite il cliente.",
    signed: "Firmato",
    signed_note: "Ciascuna parte firma una copia. Il calendario e le condizioni di fornitura ne fanno parte.",
    for_party: "Per",
    name_and_date: "Nome e data",
    headings: ["Lotto", "Scadenza", "Quantità", "Valore"],
    batches: [
        "Lenti grezze, 62 mm, trattate",
        "Lenti grezze, 68 mm, trattate",
        "Lenti grezze, 74 mm, non trattate",
        "Frontali, acetato, assortiti",
        "Aste, acetato, paia",
        "Cerniere, flex, inox",
        "Naselli, silicone",
        "Viti, M1,4, in scatole da cento",
        "Astucci, rigidi, stampati",
        "Panni, microfibra, stampati",
        "Cartoni di spedizione, stampati",
    ],
    months: ["Aprile", "Luglio", "Ottobre", "Gennaio"],
    total: "Totale, al netto delle imposte",
    conditions_title: "Condizioni di fornitura",
    conditions_edition: "condizioni di fornitura, edizione del 1° gennaio 2027",
    accepted: "Letto e accettato",
    clauses: [
        "I prezzi sono fissi per la durata del contratto, in euro, al netto dell’imposta sul valore aggiunto.",
        "Un lotto è dovuto il giorno indicato nel calendario, all’indirizzo a cui è stato inviato.",
        "Le quantità si contano all’arrivo. Un conteggio diverso si regola entro cinque giorni lavorativi.",
        "Il pagamento scade trenta giorni dopo l’arrivo del lotto, con bonifico sul conto in fattura.",
        "La proprietà di un lotto passa col pagamento. Il rischio passa all’arrivo.",
        "Un lotto rifiutato all’arrivo è ritirato entro dieci giorni lavorativi, a spese del fornitore.",
        "Ciascuna parte può porre fine al contratto con novanta giorni di preavviso scritto.",
        "I lotti già in calendario alla fine del preavviso sono forniti e pagati come previsto.",
        "Nessuna parte risponde di un ritardo dovuto a un evento fuori dal suo ragionevole controllo.",
        "Il contratto è regolato dalla legge francese, e le controversie vanno al foro di Aix-en-Provence.",
        "Una modifica a un lotto in calendario ha effetto solo se le due parti la concordano per iscritto.",
        "Il fornitore conserva un certificato di conformità per lotto per tre anni dall’arrivo.",
        "I marchi del cliente possono andare su cartoni e astucci per la durata del contratto, e per nessun altro scopo.",
        "Nessuna parte può cedere il contratto ad altri senza il consenso scritto dell’altra.",
        "Le comunicazioni si fanno per iscritto, agli indirizzi stampati sulla prima pagina.",
        "Questo fascicolo, il suo calendario e queste condizioni sono tutto ciò che le parti hanno convenuto.",
    ],
};

/// The pack in Spanish.
const SPANISH: Words = Words {
    title: "Contrato de suministro",
    drawn_up: "redactado el",
    drawn_up_on: "12 de marzo de 2027",
    supplier: "Proveedor",
    customer: "Cliente",
    vat: "IVA",
    letterhead: "Membrete",
    made_of: "De qué se compone este dosier",
    stands_on: [
        "Este dosier se apoya en tres hojas que el cliente envió como archivos PDF. La hoja con membrete",
        "está bajo esta página. Una hoja de continuación lisa está bajo cada página del calendario. La",
        "página de condiciones generales del final es la tercera hoja, tomada entera y contada como las demás.",
    ],
    stamped: [
        "Ninguna de las tres se redibuja. El programa lee cada archivo, trae su página como dibujo y",
        "la estampa bajo el texto: así un membrete sale de la impresora como lo hizo su dueño, y",
        "las condiciones de la última página son las archivadas, al pie de la letra.",
    ],
    in_it: "Qué contiene",
    page: "Página",
    pages: "Páginas",
    to: "a",
    of: "de",
    front_sheet: "Esta página, en la hoja con membrete.",
    schedule_before: "El calendario de entregas, ",
    schedule_after: " filas, en la hoja de continuación.",
    conditions_entry: "Las condiciones de suministro, tal como las dio el cliente.",
    signed: "Firmado",
    signed_note: "Cada parte firma un ejemplar. El calendario y las condiciones de suministro forman parte de él.",
    for_party: "Por",
    name_and_date: "Nombre y fecha",
    headings: ["Lote", "Entrega", "Cantidad", "Valor"],
    batches: [
        "Lentes en bruto, 62 mm, tratadas",
        "Lentes en bruto, 68 mm, tratadas",
        "Lentes en bruto, 74 mm, sin tratar",
        "Frentes de montura, acetato, surtidos",
        "Varillas de montura, acetato, pares",
        "Bisagras, de muelle, inoxidables",
        "Plaquetas, silicona",
        "Tornillos, M1,4, en cajas de cien",
        "Estuches, rígidos, impresos",
        "Gamuzas, microfibra, impresas",
        "Cajas de envío, impresas",
    ],
    months: ["Abril", "Julio", "Octubre", "Enero"],
    total: "Total, antes de impuestos",
    conditions_title: "Condiciones de suministro",
    conditions_edition: "condiciones de suministro, edición del 1 de enero de 2027",
    accepted: "Leído y aceptado",
    clauses: [
        "Los precios son firmes durante este contrato, en euros, sin impuesto sobre el valor añadido.",
        "Un lote se entrega el día que indica el calendario, en la dirección a la que se envió.",
        "Las cantidades se cuentan a la llegada. Una diferencia en el recuento se resuelve en cinco días hábiles.",
        "El pago vence treinta días después de la llegada del lote, por transferencia a la cuenta de la factura.",
        "La propiedad de un lote pasa con el pago. El riesgo pasa con la llegada.",
        "Un lote rechazado a la llegada se recoge en diez días hábiles, a cargo del proveedor.",
        "Cualquiera de las partes puede poner fin a este contrato con noventa días de preaviso, por escrito.",
        "Los lotes ya previstos al final del preaviso se suministran y pagan según lo previsto.",
        "Ninguna parte responde de un retraso causado por un hecho ajeno a su control razonable.",
        "Este contrato se rige por la ley francesa, y los litigios se someten a los tribunales de Aix-en-Provence.",
        "Un cambio en un lote previsto solo surte efecto cuando ambas partes lo acuerdan por escrito.",
        "El proveedor guarda un certificado de conformidad por lote durante tres años tras su llegada.",
        "Las marcas del cliente pueden ir en cajas y estuches durante el contrato, y para nada más.",
        "Ninguna parte puede ceder este contrato a un tercero sin el consentimiento escrito de la otra.",
        "Las notificaciones se hacen por escrito, a las direcciones impresas en la primera página.",
        "Este dosier, su calendario y estas condiciones son todo lo que las partes acordaron.",
    ],
};

/// The pack in German.
const GERMAN: Words = Words {
    title: "Liefervertrag",
    drawn_up: "aufgesetzt am",
    drawn_up_on: "12. März 2027",
    supplier: "Lieferant",
    customer: "Kunde",
    vat: "USt-IdNr.",
    letterhead: "Briefkopf",
    made_of: "Woraus diese Mappe besteht",
    stands_on: [
        "Diese Mappe steht auf drei Blättern, die der Kunde als PDF geschickt hat. Das Briefkopfblatt",
        "liegt unter dieser Seite. Ein schlichtes Folgeblatt liegt unter jeder Seite des Lieferplans.",
        "Die Seite mit den Lieferbedingungen hinten ist das dritte Blatt, ganz übernommen und mitgezählt.",
    ],
    stamped: [
        "Keines der drei wird neu gezeichnet. Das Team liest jede Datei, holt ihre Seite als Zeichnung",
        "herein und legt sie unter den Text — so kommt ein Briefkopf aus dem Drucker, wie sein Inhaber",
        "ihn gestaltet hat, und die Bedingungen auf der letzten Seite sind die hinterlegten, Wort für Wort.",
    ],
    in_it: "Was sie enthält",
    page: "Seite",
    pages: "Seiten",
    to: "bis",
    of: "von",
    front_sheet: "Diese Seite, auf dem Briefkopfblatt.",
    schedule_before: "Der Lieferplan, ",
    schedule_after: " Zeilen, auf dem Folgeblatt.",
    conditions_entry: "Die Lieferbedingungen, wie der Kunde sie geliefert hat.",
    signed: "Unterschrieben",
    signed_note: "Jede Partei unterschreibt ein Exemplar. Lieferplan und Lieferbedingungen gehören dazu.",
    for_party: "Für",
    name_and_date: "Name und Datum",
    headings: ["Charge", "Fällig", "Menge", "Wert"],
    batches: [
        "Brillenglasrohlinge, 62 mm, beschichtet",
        "Brillenglasrohlinge, 68 mm, beschichtet",
        "Brillenglasrohlinge, 74 mm, unbeschichtet",
        "Brillenfronten, Acetat, sortiert",
        "Brillenbügel, Acetat, Paare",
        "Scharniere, gefedert, Edelstahl",
        "Nasenpads, Silikon",
        "Schrauben, M1,4, zu je hundert",
        "Etuis, hart, bedruckt",
        "Putztücher, Mikrofaser, bedruckt",
        "Versandkartons, bedruckt",
    ],
    months: ["April", "Juli", "Oktober", "Januar"],
    total: "Summe, vor Steuern",
    conditions_title: "Lieferbedingungen",
    conditions_edition: "Lieferbedingungen, Fassung vom 1. Januar 2027",
    accepted: "Gelesen und angenommen",
    clauses: [
        "Die Preise gelten fest für die Laufzeit, in Euro, zuzüglich Mehrwertsteuer.",
        "Eine Charge ist am Termin des Lieferplans fällig, und zwar an der Adresse, an die dieser geschickt wurde.",
        "Mengen werden bei Ankunft gezählt. Abweichungen werden binnen fünf Werktagen geklärt.",
        "Zahlung dreißig Tage nach Ankunft der Charge, per Überweisung auf das Rechnungskonto.",
        "Das Eigentum geht mit der Zahlung über, die Gefahr mit der Ankunft.",
        "Eine abgelehnte Charge holt der Lieferant binnen zehn Werktagen auf eigene Kosten ab.",
        "Jede Partei kann diesen Vertrag mit neunzig Tagen Frist schriftlich kündigen.",
        "Chargen, die bei Fristende bereits geplant sind, werden wie geplant geliefert und bezahlt.",
        "Keine Partei haftet für Verzug durch Ereignisse außerhalb ihres Einflusses.",
        "Es gilt französisches Recht; Gerichtsstand ist Aix-en-Provence.",
        "Eine Änderung einer Charge gilt nur, wenn beide Parteien schriftlich zustimmen.",
        "Der Lieferant bewahrt je Charge drei Jahre eine Konformitätsbescheinigung auf.",
        "Die Marken des Kunden dürfen nur während der Laufzeit auf Kartons und Etuis stehen.",
        "Keine Partei darf diesen Vertrag ohne schriftliche Zustimmung übertragen.",
        "Mitteilungen erfolgen schriftlich an die Adressen auf der ersten Seite.",
        "Diese Mappe, ihr Lieferplan und diese Bedingungen bilden die gesamte Vereinbarung.",
    ],
};

/// Every language the pack is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// Draws a line of text with its left edge at `x` and its baseline at `y`.
fn text(content: &mut Content, font: &FontHandle, size: f64, x: f64, y: f64, color: Rgb, s: &str) {
    let _ = content.set_fill(color);
    content.begin_text();
    let _ = content.set_font(font, size);
    let _ = content.text_origin(x, y);
    content.show_glyphs(&font.glyphs(s));
    content.end_text();
}

/// Draws a line of text whose right edge sits at `right`.
fn text_right(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    right: f64,
    y: f64,
    color: Rgb,
    s: &str,
) {
    text(
        content,
        font,
        size,
        right - font.measure(s, size),
        y,
        color,
        s,
    );
}

/// A horizontal rule from `x1` to `x2` at height `y`.
fn rule(
    content: &mut Content,
    x1: f64,
    x2: f64,
    y: f64,
    width: f64,
    color: Rgb,
) -> Result<(), hqf_pdf::Error> {
    content.set_stroke(color)?;
    content.set_line_width(width)?;
    content.move_to(x1, y)?;
    content.line_to(x2, y)?;
    content.stroke();
    Ok(())
}

/// A rule across the whole text width, at height `y`.
fn full_rule(content: &mut Content, y: f64, width: f64, color: Rgb) -> Result<(), hqf_pdf::Error> {
    rule(content, LEFT, RIGHT, y, width, color)
}

/// The line of small print under the firm's name on the headed sheet.
fn letterhead_address(words: &Words) -> String {
    format!(
        "{SUPPLIER_STREET} — {SUPPLIER_TOWN} — {} {SUPPLIER_VAT}",
        words.vat
    )
}

/// The one line the continuation sheet carries, which is the firm and where it
/// is.
fn continuation_address() -> String {
    format!("{SUPPLIER} — {SUPPLIER_STREET}, {SUPPLIER_TOWN}")
}

/// A tax number as an address block writes it.
fn vat_line(words: &Words, number: &str) -> String {
    format!("{} {number}", words.vat)
}

/// Puts a one-page document together from what a caller draws on it, the fields
/// a reader fills in on it and the annotations laid over it.
fn one_page_sheet(
    font_path: &Path,
    fields: Vec<Field>,
    annotations: Vec<Annotation>,
    draw: impl FnOnce(&mut Document, &mut Content, &FontHandle) -> Result<(), hqf_pdf::Error>,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(font_path)?)?);

    let mut content = Content::new();
    draw(&mut doc, &mut content, &font)?;

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

    Ok(doc.to_bytes()?)
}

/// The headed sheet: a band across the top with the firm's name and address in
/// it, on a layer of its own that paper printed with the band already can leave
/// off.
fn a_headed_sheet(font_path: &Path, words: &Words) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    one_page_sheet(font_path, Vec::new(), Vec::new(), |doc, content, font| {
        let band = doc.add_layer(Layer::new(words.letterhead))?;
        content.begin_layer(&band);
        content.save_state();
        content.set_fill_rgb(0.91, 0.94, 0.98)?;
        content.rect(0.0, 742.0, PAGE_WIDTH, 100.0)?;
        content.fill();
        content.set_fill(ACCENT)?;
        content.rect(0.0, 738.0, PAGE_WIDTH, 4.0)?;
        content.fill();
        content.restore_state();

        text(content, font, 22.0, LEFT, 786.0, INK, SUPPLIER);
        text(
            content,
            font,
            9.0,
            LEFT,
            764.0,
            MUTED,
            &letterhead_address(words),
        );
        content.end_marked();
        Ok(())
    })
}

/// The continuation sheet: the firm's name small at the top, between two
/// hairlines.
fn a_continuation_sheet(font_path: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    one_page_sheet(font_path, Vec::new(), Vec::new(), |_, content, font| {
        text(
            content,
            font,
            8.0,
            LEFT,
            806.0,
            MUTED,
            &continuation_address(),
        );
        full_rule(content, 800.0, 0.5, ACCENT)?;
        full_rule(content, 64.0, 0.5, Rgb::gray(0.78))
    })
}

/// One clause as the conditions sheet numbers it.
fn clause(words: &Words, index: usize) -> String {
    format!("{}. {}", index + 1, words.clauses[index])
}

/// The line at the foot of the conditions sheet, which says whose conditions
/// they are and which edition.
fn conditions_foot(words: &Words) -> String {
    format!("{SUPPLIER} — {}", words.conditions_edition)
}

/// The conditions sheet: a heading, the standing clauses, one to a line, and
/// the box a reader ticks to accept them.
fn a_conditions_sheet(
    font_path: &Path,
    words: &Words,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let (box_x, box_y, side) = ACCEPTED_BOX;
    let accepted = CheckBox::new("accepted", box_x, box_y, side, side).into();
    let framed = Square::new(box_x - 3.0, box_y - 3.0, side + 6.0, side + 6.0)
        .color(ACCENT)
        .into();
    one_page_sheet(
        font_path,
        vec![accepted],
        vec![framed],
        |_, content, font| {
            text(
                content,
                font,
                14.0,
                LEFT,
                780.0,
                INK,
                words.conditions_title,
            );
            full_rule(content, 770.0, 0.8, ACCENT)?;

            let mut y = 744.0;
            for index in 0..words.clauses.len() {
                text(content, font, 8.5, LEFT, y, INK, &clause(words, index));
                y -= 26.0;
            }

            content.set_stroke(MUTED)?;
            content.set_line_width(0.6)?;
            content.rect(box_x, box_y, side, side)?;
            content.stroke();
            text(
                content,
                font,
                8.5,
                box_x + side + 6.0,
                box_y + 2.0,
                INK,
                words.accepted,
            );
            text(
                content,
                font,
                8.0,
                LEFT,
                96.0,
                MUTED,
                &conditions_foot(words),
            );
            Ok(())
        },
    )
}

/// One line of the schedule: on which day of the quarter it is due, how many,
/// and the price of one.
///
/// What is delivered is not here: it is a word, and it lives with the other
/// words of its language.
struct Batch {
    /// The day of the quarter's first month it is due on.
    day: u32,
    /// How many.
    quantity: u32,
    /// The price of one, before tax.
    unit_price: f64,
}

/// The batches a quarter delivers.
const BATCHES: &[Batch] = &[
    Batch {
        day: 6,
        quantity: 1200,
        unit_price: 7.20,
    },
    Batch {
        day: 6,
        quantity: 900,
        unit_price: 8.40,
    },
    Batch {
        day: 9,
        quantity: 640,
        unit_price: 6.15,
    },
    Batch {
        day: 13,
        quantity: 480,
        unit_price: 11.90,
    },
    Batch {
        day: 13,
        quantity: 480,
        unit_price: 4.35,
    },
    Batch {
        day: 17,
        quantity: 2400,
        unit_price: 0.95,
    },
    Batch {
        day: 17,
        quantity: 3600,
        unit_price: 0.22,
    },
    Batch {
        day: 20,
        quantity: 120,
        unit_price: 3.10,
    },
    Batch {
        day: 24,
        quantity: 1500,
        unit_price: 2.65,
    },
    Batch {
        day: 24,
        quantity: 3000,
        unit_price: 0.48,
    },
    Batch {
        day: 27,
        quantity: 300,
        unit_price: 1.75,
    },
];

/// The year each quarter's batches are due in, in the order the schedule runs
/// them. Which month it is is a word, and it lives with the words.
const YEARS: [u32; 4] = [2027, 2027, 2027, 2028];

/// The day a batch is due, as the schedule writes it.
fn due(words: &Words, batch: &Batch, quarter: usize) -> String {
    format!("{} {} {}", batch.day, words.months[quarter], YEARS[quarter])
}

/// An amount, as a schedule writes it: "8 640.00".
fn amount(value: f64) -> String {
    let fixed = format!("{value:.2}");
    let (units, hundredths) = fixed.split_once('.').unwrap_or((fixed.as_str(), "00"));

    let mut grouped = String::new();
    for (index, digit) in units.chars().enumerate() {
        if index > 0 && (units.len() - index) % 3 == 0 {
            grouped.push(' ');
        }
        grouped.push(digit);
    }
    format!("{grouped}.{hundredths}")
}

/// The width of each column of the schedule, in points, the first taking
/// whatever the other three leave.
const DUE_COLUMN: f64 = 92.0;
const QUANTITY_COLUMN: f64 = 58.0;
const VALUE_COLUMN: f64 = 78.0;

/// How much of a cell its text leaves free on each side, and above and below.
const CELL_PAD: (f64, f64) = (6.0, 5.0);

/// The schedule, as one table: a heading drawn again on every page, every batch
/// of every quarter, and the total of the lot.
fn schedule<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let columns = Columns::new(
        vec![
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(DUE_COLUMN),
            ColumnWidth::Points(QUANTITY_COLUMN),
            ColumnWidth::Points(VALUE_COLUMN),
        ],
        TABLE_WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.header(1);
    table
        .rule(Rule::Frame, Stroke::new(0.8, ACCENT))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.78)))
        .rule(Rule::Horizontal(1), Stroke::new(0.8, ACCENT));
    table
        .fill(Area::EvenRows, Rgb::gray(0.97))
        .fill(Area::Header, ACCENT);

    let pad = Padding::symmetric(CELL_PAD.0, CELL_PAD.1);
    let heading = |label: &str, align| {
        Cell::new(font, 9.0, label)
            .padding(pad)
            .align(align)
            .color(Rgb::gray(1.0))
            .valign(VAlign::Middle)
    };
    table.push(
        Row::new()
            .cell(heading(words.headings[0], Align::Left))
            .cell(heading(words.headings[1], Align::Left))
            .cell(heading(words.headings[2], Align::Right))
            .cell(heading(words.headings[3], Align::Right))
            .min_height(20.0),
    );

    let mut total = 0.0;
    for quarter in 0..YEARS.len() {
        for (index, batch) in BATCHES.iter().enumerate() {
            let value = f64::from(batch.quantity) * batch.unit_price;
            total += value;
            table.push(
                Row::new()
                    .cell(Cell::new(font, 9.0, words.batches[index]).padding(pad))
                    .cell(Cell::new(font, 9.0, due(words, batch, quarter)).padding(pad))
                    .cell(
                        Cell::new(font, 9.0, batch.quantity.to_string())
                            .padding(pad)
                            .align(Align::Right),
                    )
                    .cell(
                        Cell::new(font, 9.0, amount(value))
                            .padding(pad)
                            .align(Align::Right),
                    )
                    .min_height(16.0),
            );
        }
    }

    table.push(
        Row::new()
            .cell(
                Cell::new(font, 10.0, words.total)
                    .padding(pad)
                    .align(Align::Right)
                    .span(3)
                    .margin(Margin::symmetric(0.0, 2.0)),
            )
            .cell(
                Cell::new(font, 10.0, amount(total))
                    .padding(pad)
                    .align(Align::Right)
                    .margin(Margin::symmetric(0.0, 2.0)),
            )
            .min_height(20.0),
    );

    Ok(table)
}

/// What the front page can say about the pack once the schedule has said how
/// many pages it takes.
struct Contents {
    /// How many pages the pack has in all.
    pages: usize,
    /// The first page of the schedule, and its last.
    schedule: (usize, usize),
    /// How many rows the schedule carries.
    rows: usize,
}

impl Contents {
    /// The three lines the front page lists the pack by: which pages, and what
    /// is on them.
    fn lines(&self, words: &Words) -> [(String, String); 3] {
        let (first, last) = self.schedule;
        [
            (format!("{} 1", words.page), words.front_sheet.to_owned()),
            (
                format!("{} {first} {} {last}", words.pages, words.to),
                format!(
                    "{}{}{}",
                    words.schedule_before, self.rows, words.schedule_after
                ),
            ),
            (
                format!("{} {}", words.page, self.pages),
                words.conditions_entry.to_owned(),
            ),
        ]
    }
}

/// How far the second column of the list of pages stands from the first.
const ENTRY_COLUMN: f64 = 96.0;

/// How long the rule each party signs on is, in points.
const SIGNATURE_RULE: f64 = 210.0;

/// What stands over the rule a party signs on.
fn party(words: &Words, name: &str) -> String {
    format!("{} {name}", words.for_party)
}

/// Draws the two places the parties sign, each a rule with a label under it.
fn signatures(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
) -> Result<(), hqf_pdf::Error> {
    text(content, font, 11.0, LEFT, 330.0, ACCENT, words.signed);
    text(content, font, 9.0, LEFT, 312.0, INK, words.signed_note);

    let hair = Rgb::gray(0.6);
    for (x, name) in [(LEFT, SUPPLIER), (SECOND_COLUMN, CUSTOMER)] {
        rule(content, x, x + SIGNATURE_RULE, 262.0, 0.5, hair)?;
        text(content, font, 8.0, x, 250.0, MUTED, &party(words, name));
        rule(content, x, x + SIGNATURE_RULE, 210.0, 0.5, hair)?;
        text(content, font, 8.0, x, 198.0, MUTED, words.name_and_date);
    }
    Ok(())
}

/// The line under the title: what the pack is filed as, and the day it was
/// drawn up.
fn reference_line(words: &Words) -> String {
    format!("{REFERENCE} — {} {}", words.drawn_up, words.drawn_up_on)
}

/// The pack's front page: what it is, who it is between, what it is made of,
/// what is in it, and where it is signed.
fn front_page(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    contents: &Contents,
) -> Result<(), hqf_pdf::Error> {
    text(content, font, 20.0, LEFT, 700.0, ACCENT, words.title);
    text(
        content,
        font,
        9.5,
        LEFT,
        682.0,
        MUTED,
        &reference_line(words),
    );
    full_rule(content, 672.0, 0.8, ACCENT)?;

    text(content, font, 8.0, LEFT, 652.0, MUTED, words.supplier);
    text(
        content,
        font,
        8.0,
        SECOND_COLUMN,
        652.0,
        MUTED,
        words.customer,
    );

    let supplier = [
        SUPPLIER_STREET.to_owned(),
        SUPPLIER_TOWN.to_owned(),
        vat_line(words, SUPPLIER_VAT),
    ];
    let customer = [
        CUSTOMER_STREET.to_owned(),
        CUSTOMER_TOWN.to_owned(),
        vat_line(words, CUSTOMER_VAT),
    ];
    text(content, font, 10.0, LEFT, 637.0, INK, SUPPLIER);
    text(content, font, 10.0, SECOND_COLUMN, 637.0, INK, CUSTOMER);
    let mut y = 624.0;
    for (theirs, ours) in supplier.iter().zip(customer.iter()) {
        text(content, font, 9.0, LEFT, y, MUTED, theirs);
        text(content, font, 9.0, SECOND_COLUMN, y, MUTED, ours);
        y -= 12.0;
    }

    text(content, font, 11.0, LEFT, 566.0, ACCENT, words.made_of);
    let mut y = 548.0;
    for line in words.stands_on {
        text(content, font, 9.0, LEFT, y, INK, line);
        y -= 13.0;
    }
    y -= 13.0;
    for line in words.stamped {
        text(content, font, 9.0, LEFT, y, INK, line);
        y -= 13.0;
    }

    text(content, font, 11.0, LEFT, 430.0, ACCENT, words.in_it);
    let mut y = 412.0;
    for (pages, what) in contents.lines(words) {
        text(content, font, 9.0, LEFT, y, INK, &pages);
        text(content, font, 9.0, LEFT + ENTRY_COLUMN, y, MUTED, &what);
        y -= 16.0;
    }

    signatures(content, font, words)
}

/// What every page of the pack carries at its foot.
fn page_number(words: &Words, number: usize, pages: usize) -> String {
    format!("{} {number} {} {pages}", words.page, words.of)
}

/// The fields a sheet came with, as fields of the pack's page that draws it
/// whole at the corner: each where the sheet shows it, holding what it held.
///
/// A radio group is one question over all of its buttons; every other field is
/// laid down once for each place the sheet shows it.
fn carried_fields(
    sheet: &ImportedPage,
    reader: &Reader,
    font: &FontHandle,
) -> Result<Vec<Field>, hqf_pdf::Error> {
    let mut fields = Vec::new();
    for field in sheet.form_fields(reader, 0.0, 0.0, 1.0)? {
        if field.kind == FieldKind::Radio {
            fields.push(field.radio_group()?.into());
            continue;
        }
        for place in field.one_per_place() {
            fields.push(match place.kind {
                FieldKind::Check => place.check_box()?.into(),
                FieldKind::Signature => place.signature()?.into(),
                FieldKind::Choice => place.choice(font.name(), FIELD_SIZE)?.into(),
                FieldKind::Push => place.push_button(font.name(), FIELD_SIZE)?.into(),
                _ => place.text_field(font.name(), FIELD_SIZE)?.into(),
            });
        }
    }
    Ok(fields)
}

/// Adds one page to the pack: what the pack drew over its sheet, the page
/// number, which every page carries, and the fields and the annotations the
/// sheet came with.
#[expect(
    clippy::too_many_arguments,
    reason = "the sheet, where it was read from, and the page's place in the pack are each \
              their own"
)]
fn add_page(
    doc: &mut Document,
    sheet: &ImportedPage,
    reader: &Reader,
    mut content: Content,
    font: &FontHandle,
    words: &Words,
    number: usize,
    pages: usize,
) -> Result<(), hqf_pdf::Error> {
    text_right(
        &mut content,
        font,
        8.0,
        RIGHT,
        48.0,
        MUTED,
        &page_number(words, number, pages),
    );

    let mut leaf = Page::a4();
    leaf.content = content.into_bytes();
    // A page may only draw what its resources name.
    sheet.add_to(&mut leaf);
    leaf.fields = carried_fields(sheet, reader, font)?;
    leaf.carried_annotations = doc.carry_annotations(sheet, reader, 0.0, 0.0, 1.0)?;
    doc.add_page(leaf)?;
    Ok(())
}

/// Reads a sheet named on the command line, or the one made here when none is
/// named.
fn sheet(
    given: Option<String>,
    make: impl FnOnce() -> Result<Vec<u8>, Box<dyn std::error::Error>>,
) -> Result<Reader, Box<dyn std::error::Error>> {
    let bytes = match given {
        Some(path) => fs::read(path)?,
        None => make()?,
    };
    Ok(Reader::new(bytes)?)
}

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);

    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("pack")));
    let font_path = default_font();

    let headed_sheet = sheet(args.next(), || a_headed_sheet(&font_path, words))?;
    let continuation_sheet = sheet(args.next(), || a_continuation_sheet(&font_path))?;
    let conditions_sheet = sheet(args.next(), || a_conditions_sheet(&font_path, words))?;

    let mut doc = Document::new();
    doc.set_license(licence::licensed());

    // Each sheet comes in as a form: the same page, now a drawing this document
    // can stamp wherever it likes, as many times as it likes.
    let headed = doc.import_page(&headed_sheet, 0)?;
    let continuation = doc.import_page(&continuation_sheet, 0)?;
    // The conditions sheet is taken as the part of it a reader is shown.
    let conditions = doc.import_page_from(
        &conditions_sheet,
        &PageImport::new(0).boundary(PageBoundary::Crop),
    )?;
    // The layer the headed sheet's band sits on joins this document's panel.
    let brought_in = doc.add_imported_layers(&headed, &headed_sheet);
    // Each sheet is stamped from the starting graphics state, so it draws as it
    // did on its own whatever the pack set before it.
    let initial = doc.add_ext_gstate(ExtGState::initial());

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let table = schedule(&font, words)?;

    // The schedule says how many pages it needs, so the pack's length is known
    // before a page of it is made: the front page, the schedule's pages, and
    // the conditions.
    let box_of = TableFrame::new(LEFT, TABLE_TOP, TABLE_TOP - TABLE_BOTTOM);
    let placed = table.paginate(box_of, box_of)?;
    let pages = placed.len() + 2;

    // Each page: its sheet goes down first, and what the pack draws goes on top
    // of it.
    let contents = Contents {
        pages,
        schedule: (2, placed.len() + 1),
        rows: table.row_count(),
    };

    let mut content = Content::new();
    content.draw_form_from_defaults(headed.name(), &initial, 0.0, 0.0, 1.0)?;
    front_page(&mut content, &font, words, &contents)?;
    add_page(
        &mut doc,
        &headed,
        &headed_sheet,
        content,
        &font,
        words,
        1,
        pages,
    )?;

    for (index, placement) in placed.iter().enumerate() {
        let mut content = Content::new();
        content.draw_form_from_defaults(continuation.name(), &initial, 0.0, 0.0, 1.0)?;
        placement.draw(&mut content)?;
        add_page(
            &mut doc,
            &continuation,
            &continuation_sheet,
            content,
            &font,
            words,
            index + 2,
            pages,
        )?;
    }

    // The conditions sheet carries nothing of the pack's but its page number:
    // it is a page of the pack, not an attachment to it.
    let mut content = Content::new();
    content.draw_form_from_defaults(conditions.name(), &initial, 0.0, 0.0, 1.0)?;
    add_page(
        &mut doc,
        &conditions,
        &conditions_sheet,
        content,
        &font,
        words,
        pages,
        pages,
    )?;

    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, {pages} pages, {} rows over {} of them, {} layer brought \
         in",
        bytes.len(),
        table.row_count(),
        placed.len(),
        brought_in.len()
    );
    Ok(())
}

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

    use super::{
        ACCEPTED_BOX, BATCHES, CELL_PAD, CUSTOMER, CUSTOMER_VAT, Contents, DUE_COLUMN,
        ENTRY_COLUMN, LEFT, QUANTITY_COLUMN, RIGHT, SECOND_COLUMN, SIGNATURE_RULE, SUPPLIER,
        SUPPLIER_VAT, TABLE_BOTTOM, TABLE_TOP, TABLE_WIDTH, VALUE_COLUMN, WORDS, Words, YEARS,
        clause, conditions_foot, continuation_address, default_font, due, language,
        letterhead_address, page_number, party, reference_line, schedule, vat_line,
    };

    /// The lines two languages are allowed to write the same way. Both call a
    /// page a page and several of them pages: the word is the same word, not a
    /// translation that was forgotten.
    const SPARED: [&str; 17] = [
        "page: \"Page\"",
        "pages: \"Pages\"",
        // Written the same way in German.
        r#""April""#,
        // Written the same way in Italian.
        r#"customer: "Cliente""#,
        r#"to: "a""#,
        // Written the same way in Portuguese.
        r#""Abril""#,
        r#""Entrega""#,
        r#""Lote""#,
        r#""Valor""#,
        r#"for_party: "Por""#,
        r#"name_and_date: "Nome e data""#,
        r#"of: "de""#,
        r#"page: "Página""#,
        r#"pages: "Páginas""#,
        // Written the same way in Dutch.
        r#""Juli""#,
        r#""Oktober""#,
        r#"page: "Pagina""#,
    ];

    /// The font every measurement here is taken in, which is the one the
    /// example draws with.
    fn font(document: &mut Document) -> FontHandle {
        document.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        )
    }

    /// What the front page says of the pack, worked out the way the example
    /// works it out: by laying the schedule down and counting the pages it
    /// takes.
    fn pack(font: &FontHandle, words: &Words) -> Contents {
        let table = schedule(font, words).expect("the schedule's columns fit its width");
        let box_of = TableFrame::new(LEFT, TABLE_TOP, TABLE_TOP - TABLE_BOTTOM);
        let placed = table
            .paginate(box_of, box_of)
            .expect("the schedule lays out in the room it is given");

        Contents {
            pages: placed.len() + 2,
            schedule: (2, placed.len() + 1),
            rows: table.row_count(),
        }
    }

    /// Every line the pack draws outside its table, at the size it is drawn at
    /// and with the room it has to itself.
    fn drawn_lines(words: &Words, contents: &Contents) -> Vec<(String, f64, f64)> {
        let first_block = SECOND_COLUMN - LEFT;
        let second_block = RIGHT - SECOND_COLUMN;

        let mut lines = vec![
            (letterhead_address(words), 9.0, TABLE_WIDTH),
            (continuation_address(), 8.0, TABLE_WIDTH),
            (words.conditions_title.to_owned(), 14.0, TABLE_WIDTH),
            (conditions_foot(words), 8.0, TABLE_WIDTH),
            (
                words.accepted.to_owned(),
                8.5,
                TABLE_WIDTH - ACCEPTED_BOX.2 - 6.0,
            ),
            (words.title.to_owned(), 20.0, TABLE_WIDTH),
            (reference_line(words), 9.5, TABLE_WIDTH),
            (words.supplier.to_owned(), 8.0, first_block),
            (words.customer.to_owned(), 8.0, second_block),
            (vat_line(words, SUPPLIER_VAT), 9.0, first_block),
            (vat_line(words, CUSTOMER_VAT), 9.0, second_block),
            (words.made_of.to_owned(), 11.0, TABLE_WIDTH),
            (words.in_it.to_owned(), 11.0, TABLE_WIDTH),
            (words.signed.to_owned(), 11.0, TABLE_WIDTH),
            (words.signed_note.to_owned(), 9.0, TABLE_WIDTH),
            (party(words, SUPPLIER), 8.0, SIGNATURE_RULE),
            (party(words, CUSTOMER), 8.0, SIGNATURE_RULE),
            (words.name_and_date.to_owned(), 8.0, SIGNATURE_RULE),
        ];

        for number in 1..=contents.pages {
            lines.push((page_number(words, number, contents.pages), 8.0, TABLE_WIDTH));
        }
        for index in 0..words.clauses.len() {
            lines.push((clause(words, index), 8.5, TABLE_WIDTH));
        }
        for line in words.stands_on.iter().chain(words.stamped.iter()) {
            lines.push(((*line).to_owned(), 9.0, TABLE_WIDTH));
        }
        for (pages, what) in contents.lines(words) {
            lines.push((pages, 9.0, ENTRY_COLUMN));
            lines.push((what, 9.0, TABLE_WIDTH - ENTRY_COLUMN));
        }
        lines
    }

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

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

    /// Nothing on these pages is flowed: every line is drawn where it is put,
    /// and a line that runs past its room writes over what stands beside it, or
    /// off the sheet.
    #[test]
    fn every_language_keeps_each_line_within_the_room_it_has() {
        let mut document = Document::new();
        let font = font(&mut document);

        for (named, words) in WORDS {
            let contents = pack(&font, words);

            for (line, size, room) in drawn_lines(words, &contents) {
                let measured = font.measure(&line, size);

                assert!(
                    measured <= room,
                    "the {} pack draws {line:?} over {measured:.1} points, and it \
                     has {room:.1}",
                    named.code()
                );
            }
        }
    }

    /// A cell that runs past its column wraps, and its row grows taller than
    /// the sixteen points the rows around it keep: the schedule then runs on to
    /// a page the front page has already counted out.
    #[test]
    fn every_language_fits_each_cell_of_the_schedule_on_one_line() {
        let mut document = Document::new();
        let font = font(&mut document);

        let batch_column = TABLE_WIDTH - DUE_COLUMN - QUANTITY_COLUMN - VALUE_COLUMN;
        let inside = |column: f64| CELL_PAD.0.mul_add(-2.0, column);

        for (named, words) in WORDS {
            let mut cells = vec![
                (words.headings[0].to_owned(), 9.0, batch_column),
                (words.headings[1].to_owned(), 9.0, DUE_COLUMN),
                (words.headings[2].to_owned(), 9.0, QUANTITY_COLUMN),
                (words.headings[3].to_owned(), 9.0, VALUE_COLUMN),
            ];
            for (index, batch) in BATCHES.iter().enumerate() {
                cells.push((words.batches[index].to_owned(), 9.0, batch_column));
                for quarter in 0..YEARS.len() {
                    cells.push((due(words, batch, quarter), 9.0, DUE_COLUMN));
                }
            }

            for (cell, size, column) in cells {
                let measured = font.measure(&cell, size);
                let room = inside(column);

                assert!(
                    measured <= room,
                    "the {} schedule sets {cell:?} over {measured:.1} points, and \
                     its column holds {room:.1}",
                    named.code()
                );
            }
        }
    }
}