1mod fonts;
19mod images;
20mod outline_font;
21mod page;
22mod stream;
23mod text;
24
25use std::collections::HashMap;
26use std::fmt;
27use std::io::Write;
28
29use f_office_fonts::{FontDb, FontId};
30use f_office_paint::{self as paint, DisplayList, GlyphRun, GradientStop, ImageFault, ImageFormat};
31use f_office_units::Length;
32use pdf_writer::Chunk;
33
34use crate::fonts::UsedFonts;
35use crate::images::EmittedImages;
36use crate::page::DocState;
37use crate::stream::StreamPdf;
38
39#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum Error {
42 NoPages,
44 PageSize,
46 UnknownFont(FontId),
48 UnreadableFont(FontId),
50 UnknownGlyph {
52 font: FontId,
54 glyph: u32,
56 },
57 TextRange,
59 Clip,
61 Write(String),
63}
64
65impl fmt::Display for Error {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 match self {
68 Self::NoPages => f.write_str("the display list has no page"),
69 Self::PageSize => f.write_str("a page has a size that is not positive"),
70 Self::UnknownFont(id) => write!(f, "the font database has no font {}", id.index()),
71 Self::UnreadableFont(id) => write!(f, "font {} cannot be embedded", id.index()),
72 Self::UnknownGlyph { font, glyph } => {
73 write!(f, "font {} has no glyph {glyph}", font.index())
74 }
75 Self::TextRange => f.write_str("a glyph's text range is not in its run's text"),
76 Self::Clip => f.write_str("a group's clip is not a path that krilla can build"),
77 Self::Write(message) => write!(f, "the PDF cannot be written: {message}"),
78 }
79 }
80}
81
82impl std::error::Error for Error {}
83
84#[derive(Clone, Debug, PartialEq, Eq, Hash)]
86#[non_exhaustive]
87pub enum Warning {
88 ImageSkipped {
90 format: ImageFormat,
92 fault: ImageFault,
94 },
95}
96
97impl Warning {
98 #[must_use]
101 pub fn kind(&self) -> &'static str {
102 match self {
103 Self::ImageSkipped { .. } => "pdf-image-skipped",
104 }
105 }
106}
107
108impl fmt::Display for Warning {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 match self {
111 Self::ImageSkipped { format, fault } => {
112 write!(
113 f,
114 "an image in {format} format is left out of the PDF: {fault}"
115 )
116 }
117 }
118 }
119}
120
121pub type Warnings = f_office_warnings::Warnings<Warning>;
123
124pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
126
127pub fn write_pdf(list: &DisplayList, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
138 let mut out = Vec::new();
139 let warned = write_pdf_to(list, fonts, &mut out)?;
140 Ok(Warned::new(out, warned.warnings))
141}
142
143pub fn write_pdf_to<W: Write>(
152 list: &DisplayList,
153 fonts: &FontDb,
154 writer: &mut W,
155) -> Result<Warned<()>, Error> {
156 if list.pages().is_empty() {
157 return Err(Error::NoPages);
158 }
159 let mut pdf = StreamPdf::start(writer)?;
160 let pages_ref = pdf.alloc();
161 let mut state = DocState {
162 pdf,
163 fonts: UsedFonts::new(fonts),
164 images: EmittedImages::default(),
165 ext_gstates: HashMap::new(),
166 warnings: Warnings::new(),
167 };
168 let mut page_refs = Vec::with_capacity(list.pages().len());
169 for page in list.pages() {
170 page_refs.push(page::write_page(page, pages_ref, &mut state)?);
171 }
172 state.fonts.emit_all(&mut state.pdf)?;
173 let mut pages_chunk = Chunk::new();
174 let count = i32::try_from(page_refs.len())
175 .map_err(|_| Error::Write("too many pages for PDF".into()))?;
176 pages_chunk.pages(pages_ref).kids(page_refs).count(count);
177 state.pdf.emit(pages_ref, &pages_chunk)?;
178 state.pdf.finish(pages_ref)?;
179 Ok(Warned::new((), state.warnings))
180}
181
182pub(crate) fn clip_commands(commands: &[paint::PathCommand]) -> Vec<paint::PathCommand> {
185 use paint::PathCommand::{Close, LineTo, MoveTo};
186 match *commands {
187 [MoveTo(first), LineTo(a), LineTo(b), LineTo(c), Close] => {
188 vec![
189 MoveTo(first),
190 LineTo(a),
191 LineTo(b),
192 LineTo(c),
193 LineTo(first),
194 Close,
195 ]
196 }
197 [MoveTo(first), LineTo(a), LineTo(b), LineTo(c), LineTo(last)] if last == first => {
198 vec![
199 MoveTo(first),
200 LineTo(a),
201 LineTo(b),
202 LineTo(c),
203 LineTo(last),
204 Close,
205 ]
206 }
207 _ => commands.to_vec(),
208 }
209}
210
211pub(crate) fn side_scale(side: f64, start: SideStart, stretch: f64) -> (f32, f32) {
214 let written = side / stretch;
215 let own = decimal(written);
216 if start.error(side, stretch, own) <= SIDE_ERROR {
217 return (1.0, own);
218 }
219 let mut scale = 2.0_f32;
220 for _ in 0..SIDE_SCALES {
221 let factor = printed(scale);
222 let number = nearest_printed(written, factor, to_f32(written / factor));
223 if start.error(side, factor * stretch, number) <= SIDE_ERROR {
224 return (scale, number);
225 }
226 scale = scale.next_up();
227 }
228 (1.0, own)
229}
230
231#[derive(Clone, Copy)]
233pub(crate) enum SideStart {
234 Corner,
235 Centre,
236}
237
238impl SideStart {
239 fn error(self, side: f64, scale: f64, number: f32) -> f64 {
240 let whole = (scale * printed(number) - side).abs();
241 match self {
242 Self::Corner => whole,
243 Self::Centre => {
244 let half = printed(number / 2.0);
245 let before = (scale * half - side / 2.0).abs();
246 let after = (scale * (printed(number) - half) - side / 2.0).abs();
247 before.max(after).max(whole)
248 }
249 }
250 }
251}
252
253#[expect(
254 clippy::cast_precision_loss,
255 reason = "the number of half-EMUs to the point is exact in double precision"
256)]
257const SIDE_ERROR: f64 = 0.4 / Length::UNITS_PER_POINT as f64;
258const SIDE_SCALES: usize = 4_096;
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
263pub(crate) struct Anchor {
264 pub(crate) x: Length,
265 pub(crate) foot: Length,
266 pub(crate) y: Length,
267}
268
269impl Anchor {
270 const REACH: i64 = 256 * Length::UNITS_PER_POINT;
271
272 pub(crate) fn at(height: Length, x: Length, y: Length) -> Self {
273 let whole = |length: Length| {
274 let point = Length::UNITS_PER_POINT;
275 Length::from_units(length.units().div_euclid(point) * point)
276 };
277 let foot = whole(height - y);
278 Self {
279 x: whole(x),
280 foot,
281 y: height - foot,
282 }
283 }
284
285 pub(crate) fn middle(
286 height: Length,
287 (left, top): (Length, Length),
288 (right, bottom): (Length, Length),
289 ) -> Self {
290 let half = |a: Length, b: Length| Length::from_units(a.units().midpoint(b.units()));
291 Self::at(height, half(left, right), half(top, bottom))
292 }
293
294 pub(crate) fn reaches(self, x: Length, y: Length) -> bool {
295 (x - self.x).units().abs() < Self::REACH && (y - self.y).units().abs() < Self::REACH
296 }
297
298 pub(crate) fn of_line(height: Length, x: Length, y: Length) -> Self {
299 let anchor = Self::at(height, x, y);
300 if anchor.y != y {
301 return anchor;
302 }
303 let point = Length::from_units(Length::UNITS_PER_POINT);
304 Self {
305 x: anchor.x,
306 foot: anchor.foot - point,
307 y: anchor.y + point,
308 }
309 }
310
311 pub(crate) fn matrix(self) -> [f32; 6] {
312 [1.0, 0.0, 0.0, -1.0, points(self.x), points(self.foot)]
313 }
314
315 pub(crate) fn undone_matrix(self) -> [f32; 6] {
316 [1.0, 0.0, 0.0, -1.0, -points(self.x), points(self.foot)]
317 }
318
319 pub(crate) fn turned_matrix(self, turn: paint::Turn) -> [f32; 6] {
320 let [xx, yx, xy, yy] = turn_entries(turn);
321 [xx, -yx, xy, -yy, points(self.x), points(self.foot)]
322 }
323
324 pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
325 (
326 decimal((x - self.x).points_f64()),
327 decimal((y - self.y).points_f64()),
328 )
329 }
330}
331
332#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub(crate) struct FillAnchor {
335 pub(crate) anchor: Anchor,
336 hundredths: u32,
337}
338
339impl FillAnchor {
340 const REACH: f64 = 255.0;
341
342 pub(crate) fn middle(
343 height: Length,
344 (left, top): (Length, Length),
345 (right, bottom): (Length, Length),
346 ) -> Self {
347 let anchor = Anchor::middle(height, (left, top), (right, bottom));
348 let reach = [
349 left - anchor.x,
350 right - anchor.x,
351 top - anchor.y,
352 bottom - anchor.y,
353 ]
354 .into_iter()
355 .map(|distance| distance.points_f64().abs())
356 .fold(0.0, f64::max);
357 let hundredths = if reach < Self::REACH {
358 100
359 } else {
360 hundredths_above(reach / Self::REACH)
361 };
362 Self { anchor, hundredths }
363 }
364
365 fn scale(self) -> f64 {
366 printed(to_f32(f64::from(self.hundredths) / 100.0))
367 }
368
369 pub(crate) fn matrix(self) -> [f32; 6] {
370 let scale = to_f32(self.scale());
371 let Anchor { x, foot, .. } = self.anchor;
372 [scale, 0.0, 0.0, -scale, points(x), points(foot)]
373 }
374
375 fn number(self, value: f64) -> f32 {
376 if self.hundredths == 100 {
377 return decimal(value);
378 }
379 let scale = self.scale();
380 nearest_printed(value, scale, to_f32(value / scale))
381 }
382
383 pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
384 (
385 self.number((x - self.anchor.x).points_f64()),
386 self.number((y - self.anchor.y).points_f64()),
387 )
388 }
389
390 pub(crate) fn span(self, start: Length, length: Length) -> (f32, f32) {
391 let from = start.points_f64();
392 let to = from + length.points_f64();
393 (self.number(from.min(to)), self.number(from.max(to)))
394 }
395}
396
397#[expect(
398 clippy::cast_possible_truncation,
399 clippy::cast_sign_loss,
400 reason = "the ratio of a place on a page to the reach of a fill is positive and small"
401)]
402fn hundredths_above(ratio: f64) -> u32 {
403 (ratio * 100.0).ceil() as u32
404}
405
406pub(crate) fn upright_start(
407 turn: paint::Turn,
408 anchor: Anchor,
409 origin: &paint::Glyph,
410) -> (f32, f32) {
411 let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i64::from);
412 let (dx, dy) = (
413 (origin.x - anchor.x).points_f64(),
414 (origin.y - anchor.y).points_f64(),
415 );
416 let determinant = xx * yy - xy * yx;
417 if determinant == 0 {
418 return (to_f32(dx), to_f32(dy));
419 }
420 let [xx, yx, xy, yy, determinant] = [xx, yx, xy, yy, determinant].map(exact_count);
421 let scale = f64::from(paint::Turn::SCALE);
422 (
423 to_f32((yy * dx - xy * dy) * scale / determinant),
424 to_f32((xx * dy - yx * dx) * scale / determinant),
425 )
426}
427
428#[expect(
429 clippy::cast_precision_loss,
430 reason = "the entries of a turn and their products stay far below 2^53"
431)]
432fn exact_count(count: i64) -> f64 {
433 count as f64
434}
435
436pub(crate) fn turn_entries(turn: paint::Turn) -> [f32; 4] {
437 #[expect(
438 clippy::cast_precision_loss,
439 reason = "a turn's entries are millionths of at most a few units, which f32 holds to about 1e-7"
440 )]
441 [turn.xx, turn.yx, turn.xy, turn.yy].map(|entry| entry as f32 / paint::Turn::SCALE as f32)
442}
443
444pub(crate) fn upright_run(run: &GlyphRun, turn: paint::Turn) -> GlyphRun {
445 let mut upright = run.clone();
446 upright.turn = None;
447 let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i128::from);
448 let determinant = xx * yy - xy * yx;
449 if let (Some(first), true) = (run.glyphs.first(), determinant != 0) {
450 let (x0, y0) = (first.x.units(), first.y.units());
451 let scale = i128::from(paint::Turn::SCALE);
452 let back = |value: i128| i64::try_from(value * scale / determinant).unwrap_or(0);
453 for glyph in &mut upright.glyphs {
454 let dx = i128::from(glyph.x.units() - x0);
455 let dy = i128::from(glyph.y.units() - y0);
456 glyph.x = Length::from_units(x0 + back(yy * dx - xy * dy));
457 glyph.y = Length::from_units(y0 + back(xx * dy - yx * dx));
458 }
459 }
460 upright
461}
462
463pub(crate) fn stop_offset(place: u32) -> f32 {
464 to_f32(f64::from(place.min(GradientStop::END)) / f64::from(GradientStop::END))
465}
466
467pub(crate) fn path_anchor(height: Length, commands: &[paint::PathCommand]) -> Anchor {
468 path_bounds(commands).map_or(
469 Anchor::at(height, Length::ZERO, Length::ZERO),
470 |(low, high)| Anchor::middle(height, (low.x, low.y), (high.x, high.y)),
471 )
472}
473
474pub(crate) fn path_bounds(commands: &[paint::PathCommand]) -> Option<(paint::Point, paint::Point)> {
475 use paint::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
476 let points = commands.iter().flat_map(|command| match *command {
477 MoveTo(p) | LineTo(p) => vec![p],
478 QuadTo(c, p) => vec![c, p],
479 CubicTo(c0, c1, p) => vec![c0, c1, p],
480 Close => Vec::new(),
481 });
482 points.fold(None, |bounds: Option<(paint::Point, paint::Point)>, p| {
483 Some(bounds.map_or((p, p), |(low, high)| {
484 (
485 paint::Point {
486 x: low.x.min(p.x),
487 y: low.y.min(p.y),
488 },
489 paint::Point {
490 x: high.x.max(p.x),
491 y: high.y.max(p.y),
492 },
493 )
494 }))
495 })
496}
497
498pub(crate) fn points(length: Length) -> f32 {
499 to_f32(length.points_f64())
500}
501
502pub(crate) fn decimal(value: f64) -> f32 {
503 let nearest = to_f32(value);
504 if value.abs() < 256.0 {
505 return nearest;
506 }
507 nearest_printed(value, 1.0, nearest)
508}
509
510fn nearest_printed(value: f64, scale: f64, nearest: f32) -> f32 {
511 let error = |number: f32| (scale * printed(number) - value).abs();
512 let (mut best, mut best_error) = (nearest, error(nearest));
513 let (mut above, mut below) = (nearest, nearest);
514 for _ in 0..DECIMAL_NEIGHBORS {
515 above = above.next_up();
516 below = below.next_down();
517 for number in [above, below] {
518 let found = error(number);
519 if found < best_error {
520 (best, best_error) = (number, found);
521 }
522 }
523 }
524 best
525}
526
527const DECIMAL_NEIGHBORS: usize = 2;
528
529pub(crate) fn printed(number: f32) -> f64 {
530 let magnitude = number.abs();
531 let text = if number == 0.0 || (magnitude > 1e-6 && magnitude < 1e12) {
532 ryu::Buffer::new().format(number).to_owned()
533 } else {
534 number.to_string()
535 };
536 text.parse().unwrap_or(f64::from(number))
537}
538
539#[expect(
540 clippy::cast_possible_truncation,
541 reason = "PDF content streams use f32, keeping page coordinates well below 0.001 points"
542)]
543pub(crate) fn to_f32(value: f64) -> f32 {
544 value as f32
545}
546
547#[cfg(test)]
548mod tests;