mod fonts;
mod images;
mod outline_font;
mod page;
mod stream;
mod text;
use std::collections::HashMap;
use std::fmt;
use std::io::Write;
use f_office_fonts::{FontDb, FontId};
use f_office_paint::{self as paint, DisplayList, GlyphRun, GradientStop, ImageFault, ImageFormat};
use f_office_units::Length;
use pdf_writer::Chunk;
use crate::fonts::UsedFonts;
use crate::images::EmittedImages;
use crate::page::DocState;
use crate::stream::StreamPdf;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
NoPages,
PageSize,
UnknownFont(FontId),
UnreadableFont(FontId),
UnknownGlyph {
font: FontId,
glyph: u32,
},
TextRange,
Clip,
Write(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoPages => f.write_str("the display list has no page"),
Self::PageSize => f.write_str("a page has a size that is not positive"),
Self::UnknownFont(id) => write!(f, "the font database has no font {}", id.index()),
Self::UnreadableFont(id) => write!(f, "font {} cannot be embedded", id.index()),
Self::UnknownGlyph { font, glyph } => {
write!(f, "font {} has no glyph {glyph}", font.index())
}
Self::TextRange => f.write_str("a glyph's text range is not in its run's text"),
Self::Clip => f.write_str("a group's clip is not a path that krilla can build"),
Self::Write(message) => write!(f, "the PDF cannot be written: {message}"),
}
}
}
impl std::error::Error for Error {}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Warning {
ImageSkipped {
format: ImageFormat,
fault: ImageFault,
},
}
impl Warning {
#[must_use]
pub fn kind(&self) -> &'static str {
match self {
Self::ImageSkipped { .. } => "pdf-image-skipped",
}
}
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ImageSkipped { format, fault } => {
write!(
f,
"an image in {format} format is left out of the PDF: {fault}"
)
}
}
}
}
pub type Warnings = f_office_warnings::Warnings<Warning>;
pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
pub fn write_pdf(list: &DisplayList, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
let mut out = Vec::new();
let warned = write_pdf_to(list, fonts, &mut out)?;
Ok(Warned::new(out, warned.warnings))
}
pub fn write_pdf_to<W: Write>(
list: &DisplayList,
fonts: &FontDb,
writer: &mut W,
) -> Result<Warned<()>, Error> {
if list.pages().is_empty() {
return Err(Error::NoPages);
}
let mut pdf = StreamPdf::start(writer)?;
let pages_ref = pdf.alloc();
let mut state = DocState {
pdf,
fonts: UsedFonts::new(fonts),
images: EmittedImages::default(),
ext_gstates: HashMap::new(),
warnings: Warnings::new(),
};
let mut page_refs = Vec::with_capacity(list.pages().len());
for page in list.pages() {
page_refs.push(page::write_page(page, pages_ref, &mut state)?);
}
state.fonts.emit_all(&mut state.pdf)?;
let mut pages_chunk = Chunk::new();
let count = i32::try_from(page_refs.len())
.map_err(|_| Error::Write("too many pages for PDF".into()))?;
pages_chunk.pages(pages_ref).kids(page_refs).count(count);
state.pdf.emit(pages_ref, &pages_chunk)?;
state.pdf.finish(pages_ref)?;
Ok(Warned::new((), state.warnings))
}
pub(crate) fn clip_commands(commands: &[paint::PathCommand]) -> Vec<paint::PathCommand> {
use paint::PathCommand::{Close, LineTo, MoveTo};
match *commands {
[MoveTo(first), LineTo(a), LineTo(b), LineTo(c), Close] => {
vec![
MoveTo(first),
LineTo(a),
LineTo(b),
LineTo(c),
LineTo(first),
Close,
]
}
[MoveTo(first), LineTo(a), LineTo(b), LineTo(c), LineTo(last)] if last == first => {
vec![
MoveTo(first),
LineTo(a),
LineTo(b),
LineTo(c),
LineTo(last),
Close,
]
}
_ => commands.to_vec(),
}
}
pub(crate) fn side_scale(side: f64, start: SideStart, stretch: f64) -> (f32, f32) {
let written = side / stretch;
let own = decimal(written);
if start.error(side, stretch, own) <= SIDE_ERROR {
return (1.0, own);
}
let mut scale = 2.0_f32;
for _ in 0..SIDE_SCALES {
let factor = printed(scale);
let number = nearest_printed(written, factor, to_f32(written / factor));
if start.error(side, factor * stretch, number) <= SIDE_ERROR {
return (scale, number);
}
scale = scale.next_up();
}
(1.0, own)
}
#[derive(Clone, Copy)]
pub(crate) enum SideStart {
Corner,
Centre,
}
impl SideStart {
fn error(self, side: f64, scale: f64, number: f32) -> f64 {
let whole = (scale * printed(number) - side).abs();
match self {
Self::Corner => whole,
Self::Centre => {
let half = printed(number / 2.0);
let before = (scale * half - side / 2.0).abs();
let after = (scale * (printed(number) - half) - side / 2.0).abs();
before.max(after).max(whole)
}
}
}
}
#[expect(
clippy::cast_precision_loss,
reason = "the number of half-EMUs to the point is exact in double precision"
)]
const SIDE_ERROR: f64 = 0.4 / Length::UNITS_PER_POINT as f64;
const SIDE_SCALES: usize = 4_096;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Anchor {
pub(crate) x: Length,
pub(crate) foot: Length,
pub(crate) y: Length,
}
impl Anchor {
const REACH: i64 = 256 * Length::UNITS_PER_POINT;
pub(crate) fn at(height: Length, x: Length, y: Length) -> Self {
let whole = |length: Length| {
let point = Length::UNITS_PER_POINT;
Length::from_units(length.units().div_euclid(point) * point)
};
let foot = whole(height - y);
Self {
x: whole(x),
foot,
y: height - foot,
}
}
pub(crate) fn middle(
height: Length,
(left, top): (Length, Length),
(right, bottom): (Length, Length),
) -> Self {
let half = |a: Length, b: Length| Length::from_units(a.units().midpoint(b.units()));
Self::at(height, half(left, right), half(top, bottom))
}
pub(crate) fn reaches(self, x: Length, y: Length) -> bool {
(x - self.x).units().abs() < Self::REACH && (y - self.y).units().abs() < Self::REACH
}
pub(crate) fn of_line(height: Length, x: Length, y: Length) -> Self {
let anchor = Self::at(height, x, y);
if anchor.y != y {
return anchor;
}
let point = Length::from_units(Length::UNITS_PER_POINT);
Self {
x: anchor.x,
foot: anchor.foot - point,
y: anchor.y + point,
}
}
pub(crate) fn matrix(self) -> [f32; 6] {
[1.0, 0.0, 0.0, -1.0, points(self.x), points(self.foot)]
}
pub(crate) fn undone_matrix(self) -> [f32; 6] {
[1.0, 0.0, 0.0, -1.0, -points(self.x), points(self.foot)]
}
pub(crate) fn turned_matrix(self, turn: paint::Turn) -> [f32; 6] {
let [xx, yx, xy, yy] = turn_entries(turn);
[xx, -yx, xy, -yy, points(self.x), points(self.foot)]
}
pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
(
decimal(exact_points(x - self.x)),
decimal(exact_points(y - self.y)),
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FillAnchor {
pub(crate) anchor: Anchor,
hundredths: u32,
}
impl FillAnchor {
const REACH: f64 = 255.0;
pub(crate) fn middle(
height: Length,
(left, top): (Length, Length),
(right, bottom): (Length, Length),
) -> Self {
let anchor = Anchor::middle(height, (left, top), (right, bottom));
let reach = [
left - anchor.x,
right - anchor.x,
top - anchor.y,
bottom - anchor.y,
]
.into_iter()
.map(|distance| exact_points(distance).abs())
.fold(0.0, f64::max);
let hundredths = if reach < Self::REACH {
100
} else {
hundredths_above(reach / Self::REACH)
};
Self { anchor, hundredths }
}
fn scale(self) -> f64 {
printed(to_f32(f64::from(self.hundredths) / 100.0))
}
pub(crate) fn matrix(self) -> [f32; 6] {
let scale = to_f32(self.scale());
let Anchor { x, foot, .. } = self.anchor;
[scale, 0.0, 0.0, -scale, points(x), points(foot)]
}
fn number(self, value: f64) -> f32 {
if self.hundredths == 100 {
return decimal(value);
}
let scale = self.scale();
nearest_printed(value, scale, to_f32(value / scale))
}
pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
(
self.number(exact_points(x - self.anchor.x)),
self.number(exact_points(y - self.anchor.y)),
)
}
pub(crate) fn span(self, start: Length, length: Length) -> (f32, f32) {
let from = exact_points(start);
let to = from + exact_points(length);
(self.number(from.min(to)), self.number(from.max(to)))
}
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the ratio of a place on a page to the reach of a fill is positive and small"
)]
fn hundredths_above(ratio: f64) -> u32 {
(ratio * 100.0).ceil() as u32
}
pub(crate) fn upright_start(
turn: paint::Turn,
anchor: Anchor,
origin: &paint::Glyph,
) -> (f32, f32) {
let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i64::from);
let (dx, dy) = (
exact_points(origin.x - anchor.x),
exact_points(origin.y - anchor.y),
);
let determinant = xx * yy - xy * yx;
if determinant == 0 {
return (to_f32(dx), to_f32(dy));
}
let [xx, yx, xy, yy, determinant] = [xx, yx, xy, yy, determinant].map(exact_count);
let scale = f64::from(paint::Turn::SCALE);
(
to_f32((yy * dx - xy * dy) * scale / determinant),
to_f32((xx * dy - yx * dx) * scale / determinant),
)
}
#[expect(
clippy::cast_precision_loss,
reason = "the entries of a turn and their products stay far below 2^53"
)]
fn exact_count(count: i64) -> f64 {
count as f64
}
pub(crate) fn turn_entries(turn: paint::Turn) -> [f32; 4] {
#[expect(
clippy::cast_precision_loss,
reason = "a turn's entries are millionths of at most a few units, which f32 holds to about 1e-7"
)]
[turn.xx, turn.yx, turn.xy, turn.yy].map(|entry| entry as f32 / paint::Turn::SCALE as f32)
}
pub(crate) fn upright_run(run: &GlyphRun, turn: paint::Turn) -> GlyphRun {
let mut upright = run.clone();
upright.turn = None;
let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i128::from);
let determinant = xx * yy - xy * yx;
if let (Some(first), true) = (run.glyphs.first(), determinant != 0) {
let (x0, y0) = (first.x.units(), first.y.units());
let scale = i128::from(paint::Turn::SCALE);
let back = |value: i128| i64::try_from(value * scale / determinant).unwrap_or(0);
for glyph in &mut upright.glyphs {
let dx = i128::from(glyph.x.units() - x0);
let dy = i128::from(glyph.y.units() - y0);
glyph.x = Length::from_units(x0 + back(yy * dx - xy * dy));
glyph.y = Length::from_units(y0 + back(xx * dy - yx * dx));
}
}
upright
}
pub(crate) fn stop_offset(place: u32) -> f32 {
to_f32(f64::from(place.min(GradientStop::END)) / f64::from(GradientStop::END))
}
pub(crate) fn path_anchor(height: Length, commands: &[paint::PathCommand]) -> Anchor {
path_bounds(commands).map_or(
Anchor::at(height, Length::ZERO, Length::ZERO),
|(low, high)| Anchor::middle(height, (low.x, low.y), (high.x, high.y)),
)
}
pub(crate) fn path_bounds(commands: &[paint::PathCommand]) -> Option<(paint::Point, paint::Point)> {
use paint::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
let points = commands.iter().flat_map(|command| match *command {
MoveTo(p) | LineTo(p) => vec![p],
QuadTo(c, p) => vec![c, p],
CubicTo(c0, c1, p) => vec![c0, c1, p],
Close => Vec::new(),
});
points.fold(None, |bounds: Option<(paint::Point, paint::Point)>, p| {
Some(bounds.map_or((p, p), |(low, high)| {
(
paint::Point {
x: low.x.min(p.x),
y: low.y.min(p.y),
},
paint::Point {
x: high.x.max(p.x),
y: high.y.max(p.y),
},
)
}))
})
}
pub(crate) fn points(length: Length) -> f32 {
to_f32(exact_points(length))
}
pub(crate) fn decimal(value: f64) -> f32 {
let nearest = to_f32(value);
if value.abs() < 256.0 {
return nearest;
}
nearest_printed(value, 1.0, nearest)
}
fn nearest_printed(value: f64, scale: f64, nearest: f32) -> f32 {
let error = |number: f32| (scale * printed(number) - value).abs();
let (mut best, mut best_error) = (nearest, error(nearest));
let (mut above, mut below) = (nearest, nearest);
for _ in 0..DECIMAL_NEIGHBORS {
above = above.next_up();
below = below.next_down();
for number in [above, below] {
let found = error(number);
if found < best_error {
(best, best_error) = (number, found);
}
}
}
best
}
const DECIMAL_NEIGHBORS: usize = 2;
pub(crate) fn printed(number: f32) -> f64 {
let magnitude = number.abs();
let text = if number == 0.0 || (magnitude > 1e-6 && magnitude < 1e12) {
ryu::Buffer::new().format(number).to_owned()
} else {
number.to_string()
};
text.parse().unwrap_or(f64::from(number))
}
#[expect(
clippy::cast_precision_loss,
reason = "page coordinates stay far below 2^53 half-EMUs, so the conversion is exact"
)]
pub(crate) fn exact_points(length: Length) -> f64 {
length.units() as f64 / Length::UNITS_PER_POINT as f64
}
#[expect(
clippy::cast_possible_truncation,
reason = "PDF content streams use f32, keeping page coordinates well below 0.001 points"
)]
pub(crate) fn to_f32(value: f64) -> f32 {
value as f32
}
#[cfg(test)]
mod tests;