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 | //! Sets paragraphs whose style changes inside them: sizes that shift mid-line,
//! a total that is underlined, and a word that turns underlined halfway
//! through. Under them, a heading set hollow and thickened, rules set where
//! they are told rather than where the font puts them, a long reference broken
//! after its slashes and cut where nothing else will do, and a paragraph
//! centred in a box, with what its lines measure said under it. Last, two
//! prices in two styles lined up on their decimal points by a tab stop, and a
//! justified paragraph whose closing line goes flush right. A second page sets
//! a table of contents whose dots lead from each title to its page number in
//! the title's own size, and the same three lines of figures twice: as tall as
//! the largest style on them, then as tall as the style each opens in.
//!
//! Each block is laid out in the same box, so a line is as tall as the tallest
//! style standing on it, and an underline is drawn where each font says one
//! goes.
//!
//! The paragraphs are held in `Words`, once per language, and `HQF_PDF_LANG`
//! picks which set is set. Each is cut around the run whose style changes, so
//! that a language says what it has to say around the same three pieces.
//!
//! Usage: `cargo run --example write_rich_text -- tmp/rich.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_rich_text -- tmp/riche.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{
FirstBaseline, LeadingRule, Overlong, RichLine, RichText, Style, TabAlign, TabMethod, VAlign,
};
use hqf_pdf::{Align, 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 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")
}
/// The left edge of every box, in points.
const LEFT: f64 = 56.0;
/// The width every paragraph is broken to.
const WIDTH: f64 = 420.0;
/// The top of the first box.
const TOP: f64 = 760.0;
/// The gap between one block and the next.
const GAP: f64 = 26.0;
/// The sum the first paragraph is about. A total is not language.
const AMOUNT: &str = "1 240.00 EUR";
/// The reference broken in a narrow box: an address that breaks after its
/// slashes, and a code with nowhere to break but where the box cuts it.
const REFERENCE: &str =
"hqf-pdf.com/examples/rich-text/overlong/ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
/// The two prices lined up on their decimal points. A price is not language.
const PRICES: [&str; 2] = ["18.50", "1240.05"];
/// Where the decimal points of the prices stand, from the left edge of the box.
const PRICE_STOP: f64 = 300.0;
/// How wide the box the reference is broken in is, in points.
const NARROW: f64 = 150.0;
/// How tall the box the centred paragraph sits in is, in points.
const BOX_HEIGHT: f64 = 60.0;
/// The page numbers the table of contents leads to. A page number is not
/// language.
const PAGES: [&str; 3] = ["3", "8", "15"];
/// The amounts set beside the labels whose lines take their height two ways. An
/// amount is not language.
const FIGURES: [&str; 3] = ["1 240.00", "248.00", "1 488.00"];
/// How wide each of the two columns of figures is, in points.
const COLUMN: f64 = 200.0;
/// The words the page is set in, one set per language.
///
/// Every paragraph is cut around the run that carries the style being shown, so
/// the piece that is underlined, enlarged or coloured is a piece of the
/// sentence rather than a sentence of its own.
#[derive(Debug)]
struct Words {
/// The line at the head of the page.
title: &'static str,
/// The first paragraph, cut around the amount it names.
due: [&'static str; 2],
/// The second, cut around the run set in the largest type.
tallest: [&'static str; 3],
/// The third, cut around the run that carries its own colour.
coloured: [&'static str; 3],
/// The fourth, cut in the middle of a word: the second piece turns
/// underlined without the word being broken at the join.
joined: [&'static str; 3],
/// The fifth, cut around the run named by the alignment it is set to.
small: [&'static str; 3],
/// A heading cut around its hollow run and its thickened one.
hollow: [&'static str; 5],
/// A sentence cut around its heavy underline and its thin strikeout.
rules: [&'static str; 5],
/// What stands over the reference broken in a narrow box.
wrapped: &'static str,
/// The paragraph centred in a box.
centred: &'static str,
/// What the centred paragraph's lines measure; `{count}`, `{tall}` and
/// `{wide}` stand for how many hold words, how tall they are together and
/// how wide the widest runs.
measured: &'static str,
/// What stands over the prices.
lined_up: &'static str,
/// What each of the two prices is for.
priced: [&'static str; 2],
/// The justified paragraph whose closing line goes flush right.
closing: &'static str,
/// The line at the head of the second page.
second_title: &'static str,
/// What stands over the table of contents.
contents_intro: &'static str,
/// The titles of the table of contents: a chapter, one of its sections, and
/// a second chapter.
contents: [&'static str; 3],
/// What stands over the two columns of figures.
line_height_intro: &'static str,
/// What each of the three figures is for.
labels: [&'static str; 3],
}
impl Words {
/// The words the page is set in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "Rich text: styles, sizes, underlining, colour",
due: [
"The amount due is ",
", payable within thirty days. The balance carries interest at the \
statutory rate from the day it falls due, and no reminder has to be \
sent for it to do so.",
],
tallest: [
"A line is as tall as ",
"the largest",
" of the styles standing on it, and no taller.",
],
coloured: [
"A run can carry its own ",
"colour",
", set apart from the black around it.",
],
joined: [
"A word may change style in the middle: under",
"lined",
" is still one word, and is never broken at the join.",
],
small: [
"The small print sits in small type, ",
"flush right",
", below the body of the text.",
],
hollow: [
"A heading set ",
"hollow",
", or ",
"thickened",
" without a bolder font",
],
rules: [
"A rule can sit where it is told: ",
"a heavy underline",
" clear of the descenders, or ",
"a hairline",
" through the letters.",
],
wrapped: "A reference broken after its slashes, and cut where nothing else will do:",
centred: "This paragraph is centred, across and down, in the box drawn around it.",
measured: "{count} lines, {tall} pt tall together, the widest {wide} pt wide.",
lined_up: "Prices set in two styles, lined up on their decimal points:",
priced: ["Binding", "Cover, two colours"],
closing: "A justified paragraph can choose how its closing line is set: this one fills every line but the last to both edges, and sends the last one flush right.",
second_title: "Leaders and line height",
contents_intro: "A table of contents: dots lead from each title to its page number, set in the size of the title they follow.",
contents: [
"Styles within a paragraph",
"Rules, outlines and colour",
"Tab stops and leaders",
],
line_height_intro: "The same three lines twice. On the left, each line is as tall as the largest figure on it; on the right, as tall as the label it opens with.",
labels: ["Goods", "Delivery", "Amount due"],
};
/// The page in French.
const FRENCH: Words = Words {
title: "Texte enrichi : styles, tailles, soulignement, couleur",
due: [
"Le montant dû est de ",
", payable sous trente jours. Le solde produit des intérêts au taux légal à \
compter du jour de son échéance, sans qu’aucun rappel n’ait à être envoyé.",
],
tallest: [
"Une ligne est aussi haute que ",
"le plus grand",
" des styles qu’elle contient, et pas davantage.",
],
coloured: [
"Un passage peut avoir sa propre ",
"couleur",
", distincte du noir qui l’entoure.",
],
joined: [
"Un mot peut changer de style en son milieu : souli",
"gné",
" reste un seul mot, et n’est jamais coupé à la jointure.",
],
small: [
"Les mentions légales sont en petits caractères, ",
"alignées à droite",
", sous le corps du texte.",
],
hollow: [
"Un titre ",
"évidé",
", ou ",
"épaissi",
" sans police plus grasse",
],
rules: [
"Un filet peut se placer où on le demande : ",
"un soulignement épais",
" sous les jambages, ou ",
"un trait fin",
" à travers les lettres.",
],
wrapped: "Une référence coupée après ses barres obliques, et tranchée là où il n’y a \
pas d’autre choix :",
centred: "Ce paragraphe est centré, en largeur et en hauteur, dans le cadre tracé autour de lui.",
measured: "{count} lignes, {tall} pt de haut ensemble, la plus large de {wide} pt.",
lined_up: "Prix en deux styles, alignés sur leur séparateur décimal :",
priced: ["Reliure", "Couverture en deux couleurs"],
closing: "Dans un paragraphe justifié, la composition de la dernière ligne se choisit : ici, toutes les lignes vont d’un bord à l’autre, sauf la dernière, alignée à droite.",
second_title: "Points de conduite et hauteur de ligne",
contents_intro: "Dans une table des matières, des points de conduite relient chaque titre à son numéro de page ; ils ont la taille de caractères du titre qu’ils prolongent.",
contents: [
"Styles dans un paragraphe",
"Filets, contours et couleur",
"Taquets de tabulation et points de conduite",
],
line_height_intro: "Les trois mêmes lignes, présentées deux fois. À gauche, chaque ligne prend la hauteur du chiffre le plus gros qu’elle contient ; à droite, celle du libellé par lequel elle commence.",
labels: ["Marchandises", "Livraison", "Montant dû"],
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Opgemaakte tekst: stijlen, groottes, onderstreping, kleur",
due: [
"Het verschuldigde bedrag is",
", te betalen binnen dertig dagen. Over het saldo is vanaf de vervaldag wettelijke rente verschuldigd, zonder dat daarvoor een herinnering hoeft te worden gestuurd.",
],
tallest: [
"Een regel is zo hoog als",
"de grootste",
" van de stijlen die erop staan, en niet hoger.",
],
coloured: [
"Een stuk kan een eigen",
"kleur",
" hebben, los van het zwart eromheen.",
],
joined: [
"Een woord kan halverwege van stijl veranderen: onder",
"streept",
" is nog steeds één woord, en wordt nooit bij de naad gebroken.",
],
small: [
"De kleine lettertjes staan in kleine letter,",
"rechts uitgelijnd",
", onder de hoofdtekst.",
],
hollow: [
"Een kop gezet",
"hol",
", of",
"verdikt",
" zonder een vettere letter",
],
rules: [
"Een lijn kan staan waar ze moet:",
"een zware onderstreping",
" vrij van de onderstokken, of",
"een haarlijn",
" door de letters.",
],
wrapped: "Een kenmerk afgebroken na zijn schuine strepen, en gesneden waar niets anders kan:",
centred: "Deze alinea is gecentreerd, in de breedte en de hoogte, in het kader eromheen.",
measured: "{count} regels, samen {tall} pt hoog, de breedste {wide} pt breed.",
lined_up: "Prijzen in twee stijlen, uitgelijnd op hun decimale punt:",
priced: ["Inbinden", "Omslag, twee kleuren"],
closing: "Een uitgevulde alinea kan kiezen hoe haar laatste regel staat: deze vult alle andere regels van rand tot rand en zet de laatste rechts uitgelijnd.",
second_title: "Opvultekens en regelhoogte",
contents_intro: "Een inhoudsopgave: puntjes leiden van elke titel naar het paginanummer, in de grootte van de titel die ze volgen.",
contents: [
"Stijlen binnen een alinea",
"Lijnen, contouren en kleur",
"Tabstops en opvultekens",
],
line_height_intro: "Twee keer dezelfde drie regels. Links is elke regel zo hoog als het grootste bedrag erop, rechts zo hoog als de omschrijving waarmee hij begint.",
labels: ["Goederen", "Levering", "Te betalen"],
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Texto rico: estilos, tamanhos, sublinhado, cor",
due: [
"O montante em dívida é",
", pagável no prazo de trinta dias. O saldo vence juros à taxa legal desde o vencimento, sem necessidade de enviar qualquer aviso.",
],
tallest: [
"Uma linha é tão alta como",
"o maior",
" dos estilos que leva, e não mais.",
],
coloured: [
"Um troço pode levar a sua própria",
"cor",
", separada do preto à volta.",
],
joined: [
"Uma palavra pode mudar de estilo a meio: sub",
"linhado",
" continua a ser uma palavra, e nunca se parte na junção.",
],
small: [
"As letras miudinhas vão em corpo pequeno,",
"alinhadas à direita",
", por baixo do corpo do texto.",
],
hollow: [
"Um título composto",
"oco",
", ou",
"engrossado",
" sem um tipo de letra mais negro",
],
rules: [
"Um filete pode ficar onde se lhe diz:",
"um sublinhado grosso",
" livre das descendentes, ou",
"um filete fino",
" através das letras.",
],
wrapped: "Uma referência partida depois das barras, e cortada onde não há outra forma:",
centred: "Este parágrafo está centrado, na largura e na altura, na caixa desenhada à sua volta.",
measured: "{count} linhas, {tall} pt de altura no total, a mais larga com {wide} pt.",
lined_up: "Preços em dois estilos, alinhados pelo ponto decimal:",
priced: ["Encadernação", "Capa, duas cores"],
closing: "Um parágrafo justificado pode escolher como fica a sua última linha: este enche todas as outras de margem a margem e encosta a última à margem direita.",
second_title: "Caracteres de preenchimento e altura da linha",
contents_intro: "Um índice: os pontos levam de cada título ao seu número de página, no tamanho do título que prolongam.",
contents: [
"Estilos dentro de um parágrafo",
"Filetes, contornos e cor",
"Tabulações e caracteres de preenchimento",
],
line_height_intro: "As mesmas três linhas, duas vezes. À esquerda, cada linha é tão alta como o maior montante que leva; à direita, como a designação com que começa.",
labels: ["Mercadorias", "Entrega", "Montante em dívida"],
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Testo ricco: stili, corpi, sottolineatura, colore",
due: [
"L’importo dovuto è",
", pagabile entro trenta giorni. Il saldo produce interessi al tasso legale dalla scadenza, senza bisogno di alcun sollecito.",
],
tallest: [
"Una riga è alta quanto",
"il più grande",
" degli stili che porta, e non di più.",
],
coloured: [
"Un tratto può portare il proprio",
"colore",
", separato dal nero che lo circonda.",
],
joined: [
"Una parola può cambiare stile a metà: sotto",
"lineato",
" resta una parola, e non si spezza mai alla giunzione.",
],
small: [
"Le clausole minori stanno in corpo piccolo,",
"allineate a destra",
", sotto il corpo del testo.",
],
hollow: [
"Un titolo composto",
"vuoto",
", o",
"ispessito",
" senza un font più nero",
],
rules: [
"Un filetto può stare dove gli si dice:",
"una sottolineatura spessa",
" libera dai discendenti, o",
"un filetto sottile",
" attraverso le lettere.",
],
wrapped: "Un riferimento spezzato dopo le barre, e tagliato dove non c’è altro modo:",
centred: "Questo paragrafo è centrato, in larghezza e in altezza, nel riquadro disegnato intorno.",
measured: "{count} righe, alte {tall} pt in tutto, la più larga di {wide} pt.",
lined_up: "Prezzi in due stili, allineati sul punto decimale:",
priced: ["Rilegatura", "Copertina, due colori"],
closing: "Un paragrafo giustificato può scegliere come disporre l’ultima riga: questo riempie tutte le altre da un margine all’altro e manda l’ultima contro il margine destro.",
second_title: "Caratteri di riempimento e altezza di riga",
contents_intro: "Un indice: i puntini guidano da ogni titolo al suo numero di pagina, nel corpo del titolo che seguono.",
contents: [
"Stili all’interno di un paragrafo",
"Filetti, contorni e colore",
"Tabulazioni e caratteri di riempimento",
],
line_height_intro: "Le stesse tre righe, due volte. A sinistra ogni riga è alta quanto l’importo più grande che porta; a destra, quanto la voce con cui si apre.",
labels: ["Merci", "Consegna", "Importo dovuto"],
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Texto enriquecido: estilos, tamaños, subrayado, color",
due: [
"El importe a pagar es ",
", pagadero en treinta días. El saldo devenga intereses al tipo legal desde su vencimiento, sin necesidad de enviar ningún recordatorio.",
],
tallest: [
"Una línea es tan alta como ",
"el mayor",
" de los estilos que lleva, y no más.",
],
coloured: [
"Un tramo puede llevar su propio ",
"color",
", separado del negro que lo rodea.",
],
joined: [
"Una palabra puede cambiar de estilo a mitad: sub",
"rayado",
" sigue siendo una palabra, y nunca se corta en la unión.",
],
small: [
"La letra pequeña va en cuerpo pequeño, ",
"alineada a la derecha",
", bajo el cuerpo del texto.",
],
hollow: [
"Un título compuesto ",
"hueco",
", o ",
"engrosado",
" sin una fuente más negra",
],
rules: [
"Una raya puede ir donde se le diga: ",
"un subrayado grueso",
" libre de los descendentes, o ",
"un filete",
" a través de las letras.",
],
wrapped: "Una referencia cortada tras sus barras, y partida donde no queda otra:",
centred: "Este párrafo está centrado, a lo ancho y a lo alto, en la caja dibujada a su alrededor.",
measured: "{count} líneas, {tall} pt de alto en total, la más ancha de {wide} pt.",
lined_up: "Precios en dos estilos, alineados en su punto decimal:",
priced: ["Encuadernación", "Cubierta, dos colores"],
closing: "Un párrafo justificado puede elegir cómo se coloca su última línea: este llena todas las demás de borde a borde y envía la última contra el margen derecho.",
second_title: "Caracteres de relleno y altura de línea",
contents_intro: "Un índice: los puntos guían de cada título a su número de página, al tamaño del título al que siguen.",
contents: [
"Estilos dentro de un párrafo",
"Filetes, contornos y color",
"Tabuladores y caracteres de relleno",
],
line_height_intro: "Las mismas tres líneas, dos veces. A la izquierda, cada línea mide lo que el mayor importe que lleva; a la derecha, lo que la etiqueta con que empieza.",
labels: ["Mercancías", "Envío", "Importe a pagar"],
};
/// The page in German.
const GERMAN: Words = Words {
title: "Formatierter Text: Stile, Größen, Unterstreichung, Farbe",
due: [
"Der fällige Betrag ist ",
", zahlbar binnen dreißig Tagen. Der Restbetrag wird ab Fälligkeit zum gesetzlichen Zinssatz verzinst, ohne dass dafür eine Mahnung nötig ist.",
],
tallest: [
"Eine Zeile ist so hoch wie ",
"der größte",
" der Stile, die auf ihr stehen, und nicht höher.",
],
coloured: [
"Ein Abschnitt kann seine eigene ",
"Farbe",
" tragen, abgesetzt vom Schwarz ringsum.",
],
joined: [
"Ein Wort darf mitten im Wort den Stil wechseln: unter",
"strichen",
" bleibt ein Wort und wird an der Naht nie getrennt.",
],
small: [
"Das Kleingedruckte steht in kleiner Schrift, ",
"rechtsbündig",
", unter dem Haupttext.",
],
hollow: [
"Eine Überschrift, ",
"hohl",
" gesetzt oder ",
"verstärkt",
" ohne fettere Schrift",
],
rules: [
"Eine Linie kann stehen, wo man sie hinstellt: ",
"eine kräftige Unterstreichung",
" frei von den Unterlängen, oder ",
"eine Haarlinie",
" durch die Buchstaben.",
],
wrapped: "Eine Referenz, nach ihren Schrägstrichen umbrochen und dort getrennt, wo nichts anderes geht:",
centred: "Dieser Absatz ist in dem um ihn gezeichneten Rahmen waagrecht und senkrecht zentriert.",
measured: "{count} Zeilen, zusammen {tall} pt hoch, die breiteste {wide} pt breit.",
lined_up: "Preise in zwei Stilen, an ihrem Dezimalpunkt ausgerichtet:",
priced: ["Bindung", "Umschlag, zweifarbig"],
closing: "Ein Absatz im Blocksatz kann wählen, wie seine letzte Zeile steht: Dieser füllt alle übrigen Zeilen bis an beide Ränder und setzt die letzte rechtsbündig.",
second_title: "Füllpunkte und Zeilenhöhe",
contents_intro: "Ein Inhaltsverzeichnis: Von jedem Titel führen Füllpunkte zu seiner Seitenzahl. Die Punkte haben die Schriftgröße des Titels, hinter dem sie stehen.",
contents: [
"Schriftstile innerhalb eines Absatzes",
"Linien, Konturen und Farbe",
"Tabstopps und Füllpunkte",
],
line_height_intro: "Dieselben drei Zeilen zweimal. Links ist jede Zeile so hoch wie der Betrag in der größten Schrift, rechts so hoch wie die Bezeichnung am Zeilenanfang.",
labels: ["Warenwert", "Versand", "Zahlbetrag"],
};
/// 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); 7] = [
(Language::English, &ENGLISH),
(Language::French, &FRENCH),
(Language::German, &GERMAN),
(Language::Spanish, &SPANISH),
(Language::Italian, &ITALIAN),
(Language::Portuguese, &PORTUGUESE),
(Language::Dutch, &DUTCH),
];
/// Sets the blocks under the first five from `top` down: the hollow and
/// thickened heading, the rules set where they are told, the reference broken
/// in a narrow box, and the paragraph centred in a box with what its lines
/// measure; hands back where the last of them ends.
fn more(
content: &mut Content,
text: &FontHandle,
words: &Words,
mut top: f64,
) -> Result<f64, hqf_pdf::Error> {
let regular = Style::new(text, 11.0);
let small = Style::new(text, 8.0);
let ink = Rgb::new(0.0, 0.0, 0.0);
let hollow = Style::new(text, 17.0).outline(0.6, ink);
let thickened = Style::new(text, 17.0)
.color(Rgb::new(0.0, 0.35, 0.7))
.filled_outline(0.8, Rgb::new(0.0, 0.2, 0.45));
let heading = Style::new(text, 17.0);
// A heavy underline four points under the baseline, and a hairline three
// points over it.
let heavy = Style::new(text, 11.0).underline_at(-4.0, 1.5);
let hairline = Style::new(text, 11.0).strikethrough_at(3.0, 0.4);
let blocks_under = [
RichText::new()
.span(words.hollow[0], &heading)
.span(words.hollow[1], &hollow)
.span(words.hollow[2], &heading)
.span(words.hollow[3], &thickened)
.span(words.hollow[4], &heading),
RichText::new()
.span(words.rules[0], ®ular)
.span(words.rules[1], &heavy)
.span(words.rules[2], ®ular)
.span(words.rules[3], &hairline)
.span(words.rules[4], ®ular),
RichText::new().span(words.wrapped, ®ular),
];
for block in &blocks_under {
let lines = block.break_lines(WIDTH);
block.draw(content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP / 2.0;
}
let reference = RichText::new()
.overlong(Overlong::Break)
.cut_mark(Some('-'))
.break_after("/")
.span(REFERENCE, ®ular);
let lines = reference.break_lines(NARROW);
reference.draw(content, &lines, LEFT, top, NARROW)?;
top -= RichText::height(&lines) + GAP;
content.save_state();
content
.set_stroke_rgb(0.7, 0.7, 0.7)?
.set_line_width(0.5)?
.rect(LEFT, top - BOX_HEIGHT, WIDTH, BOX_HEIGHT)?
.stroke();
content.restore_state();
let centred = RichText::new()
.align(Align::Center)
.span(words.centred, ®ular);
let inside = WIDTH - 40.0;
let lines = centred.break_lines(inside);
let from = RichText::top_for(&lines, top, BOX_HEIGHT, VAlign::Middle);
centred.draw(content, &lines, LEFT + 20.0, from, inside)?;
top -= BOX_HEIGHT + 14.0;
let holding = lines.iter().filter(|line| !line.is_empty()).count();
let together: f64 = lines.iter().map(RichLine::height).sum();
let widest = lines
.iter()
.map(RichLine::natural_width)
.fold(0.0, f64::max);
let said = words
.measured
.replace("{count}", &holding.to_string())
.replace("{tall}", &format!("{together:.0}"))
.replace("{wide}", &format!("{widest:.0}"));
let caption = RichText::new().span(&said, &small);
let lines = caption.break_lines(WIDTH);
caption.draw(content, &lines, LEFT, top, WIDTH)?;
Ok(top - RichText::height(&lines))
}
/// Sets the prices lined up on their decimal points from `top` down, and under
/// them the justified paragraph whose closing line goes flush right.
fn settings(
content: &mut Content,
text: &FontHandle,
words: &Words,
mut top: f64,
) -> Result<(), hqf_pdf::Error> {
let regular = Style::new(text, 11.0);
let price = Style::new(text, 13.0).color(Rgb::new(0.0, 0.35, 0.7));
let over = RichText::new().span(words.lined_up, ®ular);
let lines = over.break_lines(WIDTH);
over.draw(content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP / 4.0;
let prices = RichText::new()
.tab_method(TabMethod::Ruler)
.tab_ruler([PRICE_STOP])
.tab_alignments([TabAlign::Decimal])
.span(words.priced[0], ®ular)
.span("\t", ®ular)
.span(PRICES[0], &price)
.span("\n", ®ular)
.span(words.priced[1], ®ular)
.span("\t", ®ular)
.span(PRICES[1], &price);
let lines = prices.break_lines(WIDTH);
prices.draw(content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP / 2.0;
let closing = RichText::new()
.align(Align::Justify)
.last_align(Align::Right)
.span(words.closing, ®ular);
let lines = closing.break_lines(WIDTH);
closing.draw(content, &lines, LEFT, top, WIDTH)
}
/// Sets the second page under its heading: a table of contents whose dots lead
/// from each title to its page number, and the same three lines of figures
/// twice, as tall as their largest style on the left and as the style each
/// opens in on the right.
fn leaders(content: &mut Content, text: &FontHandle, words: &Words) -> Result<(), hqf_pdf::Error> {
let regular = Style::new(text, 11.0);
let chapter = Style::new(text, 12.0);
let section = Style::new(text, 10.0);
let number = Style::new(text, 10.0).color(Rgb::new(0.0, 0.35, 0.7));
let mut top = TOP;
let over = RichText::new().span(words.contents_intro, ®ular);
let lines = over.break_lines(WIDTH);
over.draw(content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP / 4.0;
// Each break is set in the smallest style, so that it makes no line taller
// whichever line it is counted on.
let contents = RichText::new()
.tab_method(TabMethod::Ruler)
.tab_ruler([WIDTH])
.tab_alignments([TabAlign::Right])
.leader('.')
.span(words.contents[0], &chapter)
.span("\t", &chapter)
.span(PAGES[0], &number)
.span("\n", §ion)
.span(words.contents[1], §ion)
.span("\t", §ion)
.span(PAGES[1], &number)
.span("\n", §ion)
.span(words.contents[2], &chapter)
.span("\t", &chapter)
.span(PAGES[2], &number);
let lines = contents.break_lines(WIDTH);
contents.draw(content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP;
let over = RichText::new().span(words.line_height_intro, ®ular);
let lines = over.break_lines(WIDTH);
over.draw(content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP / 2.0;
let by_tallest = figures(text, words, LeadingRule::Tallest);
let lines = by_tallest.break_lines(COLUMN);
by_tallest.draw(content, &lines, LEFT, top, COLUMN)?;
let by_first = figures(text, words, LeadingRule::First);
let lines = by_first.break_lines(COLUMN);
by_first.draw(content, &lines, LEFT + WIDTH - COLUMN, top, COLUMN)
}
/// The three labels, each with its amount set larger and flush with the
/// column's right edge, every line as tall as `rule` says. The first baseline
/// sits as far below the top as the tallest ascender rises, whichever rule is
/// set, so that two columns drawn from the same top start on the same line.
fn figures<'a>(text: &'a FontHandle, words: &Words, rule: LeadingRule) -> RichText<'a> {
let label = Style::new(text, 10.0);
let figure = Style::new(text, 15.0).color(Rgb::new(0.0, 0.35, 0.7));
RichText::new()
.tab_method(TabMethod::Ruler)
.tab_ruler([COLUMN])
.tab_alignments([TabAlign::Right])
.first_baseline(FirstBaseline::Ascender)
.line_height(rule)
.span(words.labels[0], &label)
.span("\t", &label)
.span(FIGURES[0], &figure)
.span("\n", &label)
.span(words.labels[1], &label)
.span("\t", &label)
.span(FIGURES[1], &figure)
.span("\n", &label)
.span(words.labels[2], &label)
.span("\t", &label)
.span(FIGURES[2], &figure)
}
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("rich")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let font = Font::parse(fs::read(&font_path)?)?;
let mut doc = Document::new();
doc.set_license(licence::licensed());
let text = doc.add_font(font);
let regular = Style::new(&text, 11.0);
let small = Style::new(&text, 8.0);
let large = Style::new(&text, 17.0);
let marked = Style::new(&text, 11.0).underline();
let accent = Style::new(&text, 11.0).color(Rgb::new(0.0, 0.35, 0.7));
let blocks = vec![
RichText::new()
.align(Align::Justify)
.span(words.due[0], ®ular)
.span(AMOUNT, &marked)
.span(words.due[1], ®ular),
RichText::new()
.span(words.tallest[0], ®ular)
.span(words.tallest[1], &large)
.span(words.tallest[2], ®ular),
RichText::new()
.span(words.coloured[0], ®ular)
.span(words.coloured[1], &accent)
.span(words.coloured[2], ®ular),
RichText::new()
.span(words.joined[0], ®ular)
.span(words.joined[1], &marked)
.span(words.joined[2], ®ular),
RichText::new()
.align(Align::Right)
.span(words.small[0], &small)
.span(words.small[1], &small)
.span(words.small[2], &small),
];
let mut content = Content::new();
content.begin_text();
content.set_font(&text, 14.0)?;
content.text_origin(LEFT, TOP + 24.0)?;
content.show_glyphs(&text.glyphs(words.title));
content.end_text();
let mut top = TOP;
for block in &blocks {
let lines = block.break_lines(WIDTH);
block.draw(&mut content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP;
}
let top = more(&mut content, &text, words, top)?;
settings(&mut content, &text, words, top - GAP / 2.0)?;
let mut page = Page::a4();
page.content = content.into_bytes();
doc.add_page(page)?;
let mut second = Content::new();
second.begin_text();
second.set_font(&text, 14.0)?;
second.text_origin(LEFT, TOP + 24.0)?;
second.show_glyphs(&text.glyphs(words.second_title));
second.end_text();
leaders(&mut second, &text, words)?;
let mut page = Page::a4();
page.content = second.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, {} blocks",
bytes.len(),
blocks.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WORDS, language};
/// The lines two languages are allowed to write the same way. Every
/// paragraph here is a sentence, and no two languages write one alike.
const SPARED: [&str; 0] = [];
#[test]
fn every_language_sets_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:?}"
);
}
/// The fourth paragraph exists to show that a word whose halves are set in
/// two styles is still one word. A language that gives the underlined run a
/// word of its own shows nothing, and the page reads as if the run had been
/// emphasised in the ordinary way.
#[test]
fn every_language_turns_a_word_underlined_halfway_through() {
for (language, words) in WORDS {
let [before, run, after] = words.joined;
let code = language.code();
assert!(
!before.ends_with(' '),
"{code} starts the underlined run on a word of its own"
);
assert!(
!run.starts_with(' ') && !run.ends_with(' '),
"{code} pads the underlined run with spaces"
);
assert!(
after.starts_with(' '),
"{code} carries the word on past the underlining"
);
}
}
}
|