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
use crate::ffi;
/// Wrapper around FPDF_FONT obtained from a text object.
/// This is a borrowed handle — it does not own the font and must not outlive
/// the page object it was obtained from.
pub struct Font {
handle: pdfium_sys::FPDF_FONT,
}
/// Font type enum matching PDFium's FPDF_FONT_TYPE values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontType {
Unknown,
Type1,
TrueType,
Type0,
Type3,
CidType0,
CidType2,
}
impl Font {
/// Create a Font from a text page object handle.
/// Returns None if the object has no font.
///
/// # Safety
/// `obj` must be a valid `FPDF_PAGEOBJECT` handle obtained from PDFium.
pub unsafe fn from_text_object(obj: pdfium_sys::FPDF_PAGEOBJECT) -> Option<Self> {
let handle = unsafe { ffi!(FPDFTextObj_GetFont(obj)) };
if handle.is_null() {
None
} else {
Some(Font { handle })
}
}
pub fn handle(&self) -> pdfium_sys::FPDF_FONT {
self.handle
}
/// Get the base font name (PostScript name, subset prefix stripped by PDFium).
pub fn base_name(&self) -> Option<String> {
let len = unsafe {
ffi!(FPDFFont_GetBaseFontName(
self.handle,
std::ptr::null_mut(),
0
))
};
if len == 0 {
return None;
}
let mut buf: Vec<u8> = vec![0; len];
let written = unsafe {
ffi!(FPDFFont_GetBaseFontName(
self.handle,
buf.as_mut_ptr() as *mut std::ffi::c_char,
len,
))
};
if written == 0 {
return None;
}
// Strip trailing NUL
let str_len = if written > 0 && buf[written - 1] == 0 {
written - 1
} else {
written
};
Some(String::from_utf8_lossy(&buf[..str_len]).into_owned())
}
/// Get font type.
pub fn font_type(&self) -> FontType {
let t = unsafe { ffi!(FPDFFont_GetType(self.handle)) };
match t {
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_TYPE1 => FontType::Type1,
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_TRUETYPE => FontType::TrueType,
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_TYPE0 => FontType::Type0,
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_TYPE3 => FontType::Type3,
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_CID_TYPE0 => FontType::CidType0,
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_CID_TYPE2 => FontType::CidType2,
_ => FontType::Unknown,
}
}
/// Whether the font is embedded in the PDF.
pub fn is_embedded(&self) -> bool {
unsafe { ffi!(FPDFFont_GetIsEmbedded(self.handle)) != 0 }
}
/// Get font ascent for a given em size.
pub fn ascent(&self, font_size: f32) -> Option<f32> {
let mut val: f32 = 0.0;
let ok = unsafe { ffi!(FPDFFont_GetAscent(self.handle, font_size, &mut val)) };
if ok != 0 { Some(val) } else { None }
}
/// Get font descent for a given em size (typically negative).
pub fn descent(&self, font_size: f32) -> Option<f32> {
let mut val: f32 = 0.0;
let ok = unsafe { ffi!(FPDFFont_GetDescent(self.handle, font_size, &mut val)) };
if ok != 0 { Some(val) } else { None }
}
/// Get glyph width using the raw character code.
pub fn glyph_width_from_char_code(&self, char_code: u32, font_size: f32) -> Option<f32> {
let mut width: f32 = 0.0;
let ok = unsafe {
ffi!(FPDFFont_GetGlyphWidthFromCharCode(
self.handle,
char_code,
font_size,
&mut width,
))
};
if ok != 0 { Some(width) } else { None }
}
/// Walk the vector outline of the glyph for `char_code`, returning one
/// entry per path segment as `(segment_type, x, y)`. `segment_type` is the
/// raw PDFium `FPDF_SEGMENT_*` value (LINETO=0, BEZIERTO=1, MOVETO=2).
/// Segments with type `FPDF_SEGMENT_UNKNOWN` (-1) are skipped, and a point
/// that cannot be read is reported as `(type, 0.0, 0.0)` — matching the
/// platform's `hashGlyphPath` packing convention so a downstream hash of
/// these segments reproduces the platform font DB's `pathHash` key.
///
/// Returns `None` when the font has no outline for this char code
/// (e.g. whitespace / non-rendered glyph), distinct from `Some(vec![])`.
pub fn glyph_path_segments(
&self,
char_code: u32,
font_size: f32,
) -> Option<Vec<(i32, f32, f32)>> {
let glyph_path = unsafe {
ffi!(FPDFFont_GetGlyphPathFromCharCode(
self.handle,
char_code,
font_size
))
};
if glyph_path.is_null() {
return None;
}
let count = unsafe { ffi!(FPDFGlyphPath_CountGlyphSegments(glyph_path)) };
let mut segments = Vec::new();
for i in 0..count {
let segment = unsafe { ffi!(FPDFGlyphPath_GetGlyphPathSegment(glyph_path, i)) };
if segment.is_null() {
break;
}
let seg_type = unsafe { ffi!(FPDFPathSegment_GetType(segment)) };
if seg_type == pdfium_sys::FPDF_SEGMENT_UNKNOWN {
continue;
}
let mut x: f32 = 0.0;
let mut y: f32 = 0.0;
let ok = unsafe { ffi!(FPDFPathSegment_GetPoint(segment, &mut x, &mut y)) };
if ok == 0 {
x = 0.0;
y = 0.0;
}
segments.push((seg_type, x, y));
}
Some(segments)
}
/// Get glyph width using a Unicode codepoint.
pub fn glyph_width(&self, unicode: u32, font_size: f32) -> Option<f32> {
let mut width: f32 = 0.0;
let ok = unsafe {
ffi!(FPDFFont_GetGlyphWidth(
self.handle,
unicode,
font_size,
&mut width
))
};
if ok != 0 { Some(width) } else { None }
}
/// Whether the font dictionary defines a /ToUnicode CMap. When false, the
/// unicode values PDFium reports for this font's chars are derived from
/// the encoding alone and may be garbage for custom/Identity encodings.
pub fn has_to_unicode(&self) -> bool {
unsafe { ffi!(FPDFFont_HasToUnicode(self.handle)) != 0 }
}
/// Get the font's /Encoding name ("WinAnsiEncoding", "Identity-H", ...),
/// the /BaseEncoding name when /Encoding is a dict, or "Custom" for
/// font-private encodings.
pub fn encoding(&self) -> Option<String> {
let len =
unsafe { ffi!(FPDFFont_GetEncoding(self.handle, std::ptr::null_mut(), 0)) } as usize;
if len == 0 {
return None;
}
let mut buf: Vec<u8> = vec![0; len];
let written = unsafe {
ffi!(FPDFFont_GetEncoding(
self.handle,
buf.as_mut_ptr() as *mut std::ffi::c_char,
len as u64 as _,
))
} as usize;
if written == 0 {
return None;
}
let str_len = if buf[written - 1] == 0 {
written - 1
} else {
written
};
Some(String::from_utf8_lossy(&buf[..str_len]).into_owned())
}
/// Get the PostScript glyph name the font assigns to a raw char code
/// (from /Encoding /Differences, falling back to the embedded font
/// program's glyph name table). Resolve against the Adobe Glyph List to
/// recover unicode when /ToUnicode is missing.
pub fn char_glyph_name(&self, char_code: u32) -> Option<String> {
let len = unsafe {
ffi!(FPDFFont_GetCharGlyphName(
self.handle,
char_code,
std::ptr::null_mut(),
0
))
} as usize;
if len == 0 {
return None;
}
let mut buf: Vec<u8> = vec![0; len];
let written = unsafe {
ffi!(FPDFFont_GetCharGlyphName(
self.handle,
char_code,
buf.as_mut_ptr() as *mut std::ffi::c_char,
len as u64 as _,
))
} as usize;
if written == 0 {
return None;
}
let str_len = if buf[written - 1] == 0 {
written - 1
} else {
written
};
Some(String::from_utf8_lossy(&buf[..str_len]).into_owned())
}
/// Get the glyph index in the embedded font program for a raw char code.
/// Pair with glyph-path rendering for a per-glyph OCR fallback.
pub fn char_glyph_index(&self, char_code: u32) -> Option<u32> {
let idx = unsafe { ffi!(FPDFFont_GetCharGlyphIndex(self.handle, char_code)) };
if idx >= 0 { Some(idx as u32) } else { None }
}
/// Get the embedded font program bytes (decompressed FontFile/2/3 stream,
/// or the substitute font data for non-embedded fonts).
pub fn font_data(&self) -> Option<Vec<u8>> {
let mut size: usize = 0;
let ok = unsafe {
ffi!(FPDFFont_GetFontData(
self.handle,
std::ptr::null_mut(),
0,
&mut size
))
};
if ok == 0 || size == 0 {
return None;
}
let mut buf: Vec<u8> = vec![0; size];
let mut written: usize = 0;
let ok = unsafe {
ffi!(FPDFFont_GetFontData(
self.handle,
buf.as_mut_ptr(),
buf.len(),
&mut written
))
};
if ok == 0 || written == 0 {
return None;
}
buf.truncate(written);
Some(buf)
}
}