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
use printpdf::*;
static ROBOTO_TTF: &[u8] = include_bytes!("./assets/fonts/RobotoMedium.ttf");
fn main() {
// Create a new PDF document
let mut doc = PdfDocument::new("Text Example");
// Load and register an external font
let roboto = ParsedFont::from_bytes(ROBOTO_TTF, 0, &mut Vec::new()).unwrap();
let roboto_id = doc.add_font(&roboto);
// Create operations for different text styles
let ops = vec![
// Save the graphics state to allow for position resets later
Op::SaveGraphicsState,
// Start a text section (required for text operations)
Op::StartTextSection,
// Position the text cursor from the bottom left
Op::SetTextCursor {
pos: Point::new(Mm(20.0), Mm(270.0)),
},
// Set a built-in font (Helvetica) with its size
Op::SetFont {
font: PdfFontHandle::Builtin(BuiltinFont::Helvetica),
size: Pt(24.0),
},
Op::SetLineHeight { lh: Pt(24.0) },
// Set text color to blue
Op::SetFillColor {
col: Color::Rgb(Rgb {
r: 0.0,
g: 0.0,
b: 0.8,
icc_profile: None,
}),
},
// Write text with the built-in font
Op::ShowText {
items: vec![TextItem::Text("Hello from Helvetica!".to_string())],
},
// Add a line break to move down
Op::AddLineBreak,
// Change to Times Roman font
Op::SetFont {
font: PdfFontHandle::Builtin(BuiltinFont::TimesRoman),
size: Pt(18.0),
},
Op::SetLineHeight { lh: Pt(18.0) },
// Change color to dark red
Op::SetFillColor {
col: Color::Rgb(Rgb {
r: 0.8,
g: 0.0,
b: 0.0,
icc_profile: None,
}),
},
// Write text with Times Roman
Op::ShowText {
items: vec![TextItem::Text("This is Times Roman font".to_string())],
},
// Add another line break
Op::AddLineBreak,
// Use our custom Roboto font
Op::SetFont {
font: PdfFontHandle::External(roboto_id.clone()),
size: Pt(14.0),
},
Op::SetLineHeight { lh: Pt(14.0) },
// Change color to dark green
Op::SetFillColor {
col: Color::Rgb(Rgb {
r: 0.0,
g: 0.6,
b: 0.0,
icc_profile: None,
}),
},
// Write text with the custom font
Op::ShowText {
items: vec![TextItem::Text("This text uses the Roboto font".to_string())],
},
// End the text section
Op::EndTextSection,
// Restore the graphics state
Op::RestoreGraphicsState,
];
// Create a page with our operations
let page = PdfPage::new(Mm(210.0), Mm(297.0), ops);
// Save the PDF to a file
let bytes = doc
.with_pages(vec![page])
.save(&PdfSaveOptions::default(), &mut Vec::new());
std::fs::write("./text_example.pdf", bytes).unwrap();
println!("Created text_example.pdf");
}