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 | //! 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.
//!
//! 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.
//!
//! 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]`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{
Area, Cell, ColumnWidth, Columns, Frame, Margin, Padding, Row, Rule, Stroke, Table, VAlign,
};
use hqf_pdf::read::{ImportedPage, Reader};
use hqf_pdf::{Align, Document, Font, FontHandle, Page, Rgb};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
/// 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, and the day it was drawn up.
const REFERENCE: &str = "SA-2027-0088";
const DRAWN_UP: &str = "12 March 2027";
/// The box the schedule is fitted into, on whichever page it lands.
const TABLE_TOP: f64 = 780.0;
const TABLE_BOTTOM: f64 = 80.0;
/// 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.name(), 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)
}
/// Puts a one-page document together from what a caller draws on it.
fn one_page_sheet(
font_path: &Path,
draw: impl FnOnce(&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 content, &font)?;
let mut page = Page::a4();
page.content = content.into_bytes();
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.
fn a_headed_sheet(font_path: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
one_page_sheet(font_path, |content, font| {
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, "HQF Development");
text(
content,
font,
9.0,
LEFT,
764.0,
MUTED,
"42 lot les Genêts — 13480 Calas, France — VAT FR59 752 492 777",
);
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, |content, font| {
text(
content,
font,
8.0,
LEFT,
806.0,
MUTED,
"HQF Development — 42 lot les Genêts, 13480 Calas, France",
);
full_rule(content, 800.0, 0.5, ACCENT)?;
full_rule(content, 64.0, 0.5, Rgb::gray(0.78))
})
}
/// The clauses printed on the conditions sheet.
const CLAUSES: &[&str] = &[
"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 conditions sheet: a heading and the standing clauses, one to a line.
fn a_conditions_sheet(font_path: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
one_page_sheet(font_path, |content, font| {
text(
content,
font,
14.0,
LEFT,
780.0,
INK,
"Conditions of supply",
);
full_rule(content, 770.0, 0.8, ACCENT)?;
let mut y = 744.0;
for (index, clause) in CLAUSES.iter().enumerate() {
text(
content,
font,
8.5,
LEFT,
y,
INK,
&format!("{}. {clause}", index + 1),
);
y -= 26.0;
}
text(
content,
font,
8.0,
LEFT,
96.0,
MUTED,
"HQF Development — conditions of supply, edition of 1 January 2027",
);
Ok(())
})
}
/// One line of the schedule: what is delivered, on which day of the quarter,
/// how many, and the price of one.
struct Batch {
/// What is delivered.
label: &'static str,
/// 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 {
label: "Lens blanks, 62 mm, coated",
day: 6,
quantity: 1200,
unit_price: 7.20,
},
Batch {
label: "Lens blanks, 68 mm, coated",
day: 6,
quantity: 900,
unit_price: 8.40,
},
Batch {
label: "Lens blanks, 74 mm, uncoated",
day: 9,
quantity: 640,
unit_price: 6.15,
},
Batch {
label: "Frame fronts, acetate, assorted",
day: 13,
quantity: 480,
unit_price: 11.90,
},
Batch {
label: "Frame temples, acetate, pairs",
day: 13,
quantity: 480,
unit_price: 4.35,
},
Batch {
label: "Hinges, sprung, stainless",
day: 17,
quantity: 2400,
unit_price: 0.95,
},
Batch {
label: "Nose pads, silicone",
day: 17,
quantity: 3600,
unit_price: 0.22,
},
Batch {
label: "Screws, M1.4, boxed by hundred",
day: 20,
quantity: 120,
unit_price: 3.10,
},
Batch {
label: "Cases, hard, printed",
day: 24,
quantity: 1500,
unit_price: 2.65,
},
Batch {
label: "Cloths, microfibre, printed",
day: 24,
quantity: 3000,
unit_price: 0.48,
},
Batch {
label: "Cartons, shipping, printed",
day: 27,
quantity: 300,
unit_price: 1.75,
},
];
/// The quarters the schedule runs over: the month a quarter's batches are due
/// in, and its year.
const QUARTERS: &[(&str, u32)] = &[
("April", 2027),
("July", 2027),
("October", 2027),
("January", 2028),
];
/// 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 schedule, as one table: a heading drawn again on every page, every batch
/// of every quarter, and the total of the lot.
fn schedule(font: &FontHandle) -> Result<Table<'_>, hqf_pdf::Error> {
let columns = Columns::new(
vec![
ColumnWidth::Fraction(1.0),
ColumnWidth::Points(92.0),
ColumnWidth::Points(58.0),
ColumnWidth::Points(78.0),
],
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(6.0, 5.0);
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("Batch", Align::Left))
.cell(heading("Due", Align::Left))
.cell(heading("Quantity", Align::Right))
.cell(heading("Value", Align::Right))
.min_height(20.0),
);
let mut total = 0.0;
for (month, year) in QUARTERS {
for batch in BATCHES {
let value = f64::from(batch.quantity) * batch.unit_price;
total += value;
table.push(
Row::new()
.cell(Cell::new(font, 9.0, batch.label).padding(pad))
.cell(
Cell::new(font, 9.0, format!("{} {month} {year}", batch.day)).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, "Total, before tax")
.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)
}
/// The lines the front page explains the pack with, and what it stands on.
const EXPLAINED: &[&str] = &[
"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.",
"",
"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.",
];
/// 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) -> [(String, String); 3] {
let (first, last) = self.schedule;
[
(
"Page 1".to_owned(),
"This page, on the headed sheet.".to_owned(),
),
(
format!("Pages {first} to {last}"),
format!(
"The delivery schedule, {} rows, on the continuation sheet.",
self.rows
),
),
(
format!("Page {}", self.pages),
"The conditions of supply, as the customer supplied them.".to_owned(),
),
]
}
}
/// Draws the two places the parties sign, each a rule with a label under it.
fn signatures(content: &mut Content, font: &FontHandle) -> Result<(), hqf_pdf::Error> {
text(content, font, 11.0, LEFT, 330.0, ACCENT, "Signed");
text(
content,
font,
9.0,
LEFT,
312.0,
INK,
"Each party signs one copy. The schedule and the conditions of supply are part of it.",
);
let hair = Rgb::gray(0.6);
for (x, party) in [
(LEFT, "For HQF Development"),
(SECOND_COLUMN, "For Meridian Optics SAS"),
] {
rule(content, x, x + 210.0, 262.0, 0.5, hair)?;
text(content, font, 8.0, x, 250.0, MUTED, party);
rule(content, x, x + 210.0, 210.0, 0.5, hair)?;
text(content, font, 8.0, x, 198.0, MUTED, "Name and date");
}
Ok(())
}
/// 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,
contents: &Contents,
) -> Result<(), hqf_pdf::Error> {
text(content, font, 20.0, LEFT, 700.0, ACCENT, "Supply agreement");
text(
content,
font,
9.5,
LEFT,
682.0,
MUTED,
&format!("{REFERENCE} — drawn up {DRAWN_UP}"),
);
full_rule(content, 672.0, 0.8, ACCENT)?;
text(content, font, 8.0, LEFT, 652.0, MUTED, "Supplier");
text(content, font, 8.0, SECOND_COLUMN, 652.0, MUTED, "Customer");
let supplier = [
"42 lot les Genêts",
"13480 Calas, France",
"VAT FR59 752 492 777",
];
let customer = [
"18 avenue des Peupliers",
"69100 Villeurbanne, France",
"VAT FR41 512 336 908",
];
text(content, font, 10.0, LEFT, 637.0, INK, "HQF Development");
text(
content,
font,
10.0,
SECOND_COLUMN,
637.0,
INK,
"Meridian Optics SAS",
);
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,
"What this pack is made of",
);
let mut y = 548.0;
for line in EXPLAINED {
if !line.is_empty() {
text(content, font, 9.0, LEFT, y, INK, line);
}
y -= 13.0;
}
text(content, font, 11.0, LEFT, 430.0, ACCENT, "What is in it");
let mut y = 412.0;
for (pages, what) in contents.lines() {
text(content, font, 9.0, LEFT, y, INK, &pages);
text(content, font, 9.0, LEFT + 96.0, y, MUTED, &what);
y -= 16.0;
}
signatures(content, font)
}
/// Adds one page to the pack: what the pack drew over its sheet, and the page
/// number, which every page carries.
fn add_page(
doc: &mut Document,
sheet: &ImportedPage,
mut content: Content,
font: &FontHandle,
number: usize,
pages: usize,
) -> Result<(), hqf_pdf::Error> {
text_right(
&mut content,
font,
8.0,
RIGHT,
48.0,
MUTED,
&format!("Page {number} of {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);
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>,
font_path: &Path,
make: impl FnOnce(&Path) -> 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(font_path)?,
};
Ok(Reader::new(bytes)?)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = env::args().skip(1);
let out = args.next().unwrap_or_else(|| out::default_path("pack"));
let font_path = default_font();
let headed = sheet(args.next(), &font_path, a_headed_sheet)?;
let continuation = sheet(args.next(), &font_path, a_continuation_sheet)?;
let conditions = sheet(args.next(), &font_path, a_conditions_sheet)?;
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, 0)?;
let continuation = doc.import_page(&continuation, 0)?;
let conditions = doc.import_page(&conditions, 0)?;
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
let table = schedule(&font)?;
// 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 = Frame::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(headed.name(), 0.0, 0.0, 1.0)?;
front_page(&mut content, &font, &contents)?;
add_page(&mut doc, &headed, content, &font, 1, pages)?;
for (index, placement) in placed.iter().enumerate() {
let mut content = Content::new();
content.draw_form(continuation.name(), 0.0, 0.0, 1.0)?;
placement.draw(&mut content)?;
add_page(&mut doc, &continuation, content, &font, 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(conditions.name(), 0.0, 0.0, 1.0)?;
add_page(&mut doc, &conditions, content, &font, 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",
bytes.len(),
table.row_count(),
placed.len()
);
Ok(())
}
|