Paint rules and frames as native PDF rectangles

This commit is contained in:
gloamxun committed 2026-10-19 14:04:02 +08:00
1 parent 4aa1714923
commit be6f8859c2
36 files changed
+8967 -53

No files matched your search

+1251
View File
File diff suppressed because it is too large. Load diff
+516
View File
@@ -0,0 +1,516 @@
// SPDX-FileCopyrightText: 2020 Alexander Dean-Kennedy <[email protected]>
// SPDX-FileCopyrightText: 2021 Robin Krahl <[email protected]>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Image support for genpdf-rs.
use std::path;
use image::GenericImageView;
use crate::error::{Context as _, Error, ErrorKind};
use crate::{render, style};
use crate::{Alignment, Context, Element, Mm, Position, RenderResult, Rotation, Scale, Size};
/// An image to embed in the PDF.
///
/// *Only available if the `images` feature is enabled.*
///
/// This struct is a wrapper around the configurations [`printpdf::Image`][] exposes.
///
/// # Supported Formats
///
/// All formats supported by the [`image`][] should be supported by this crate. The BMP, JPEG and
/// PNG formats are well tested and known to work. Yet it is currently not possible to render
/// images with transparency, see [`printpdf` issue #98][].
///
/// Note that only the GIF, JPEG, PNG, PNM, TIFF and BMP formats are enabled by default. If you
/// want to use other formats, you have to add the `image` crate as a dependency and activate the
/// required feature.
///
/// # Example
///
/// ```
/// use std::convert::TryFrom;
/// use genpdf::elements;
/// let image = elements::Image::from_path("examples/images/test_image.jpg")
/// .expect("Failed to load test image")
/// .with_alignment(genpdf::Alignment::Center) // Center the image on the page.
/// .with_scale(genpdf::Scale::new(0.5, 2)); // Squeeze and then stretch upwards.
/// ```
///
/// [`image`]: https://lib.rs/crates/image
/// [`printpdf::Image`]: https://docs.rs/printpdf/latest/printpdf/types/plugins/graphics/two_dimensional/image/struct.Image.html
/// [`printpdf` issue #98]: https://github.com/fschutt/printpdf/issues/98
#[derive(Clone)]
pub struct Image {
data: image::DynamicImage,
/// Used for positioning if no absolute position is given.
alignment: Alignment,
/// The absolute position within the given area.
///
/// If no position is set, we use the Alignment.
position: Option<Position>,
/// Scaling of the image, default is 1:1.
scale: Scale,
/// The number of degrees of clockwise rotation.
rotation: Rotation,
/// DPI override if you know better. Defaults to `printpdf`’s default of 300 dpi.
dpi: Option<f64>,
}
impl Image {
/// Creates a new image from an already loaded image.
pub fn from_dynamic_image(data: image::DynamicImage) -> Result<Self, Error> {
if data.color().has_alpha() {
Err(Error::new(
"Images with an alpha channel are not supported",
ErrorKind::InvalidData,
))
} else {
Ok(Image {
data,
alignment: Alignment::default(),
position: None,
scale: Scale::default(),
rotation: Rotation::default(),
dpi: None,
})
}
}
fn from_image_reader<R>(reader: image::io::Reader<R>) -> Result<Self, Error>
where
R: std::io::BufRead,
R: std::io::Read,
R: std::io::Seek,
{
let image = reader
.with_guessed_format()
.context("Could not determine image format")?
.decode()
.context("Could not decode image")?;
Self::from_dynamic_image(image)
}
/// Creates a new image from the given reader.
pub fn from_reader<R>(reader: R) -> Result<Self, Error>
where
R: std::io::BufRead,
R: std::io::Read,
R: std::io::Seek,
{
Self::from_image_reader(image::io::Reader::new(reader))
}
/// Creates a new image by reading from the given path.
pub fn from_path(path: impl AsRef<path::Path>) -> Result<Self, Error> {
let path = path.as_ref();
let reader = image::io::Reader::open(path)
.with_context(|| format!("Could not read image from path {}", path.display()))?;
Self::from_image_reader(reader)
}
/// Translates the image over to position.
pub fn set_position(&mut self, position: impl Into<Position>) {
self.position = Some(position.into());
}
/// Translates the image over to position and returns it.
pub fn with_position(mut self, position: impl Into<Position>) -> Self {
self.set_position(position);
self
}
/// Scales the image.
pub fn set_scale(&mut self, scale: impl Into<Scale>) {
self.scale = scale.into();
}
/// Scales the image and returns it.
pub fn with_scale(mut self, scale: impl Into<Scale>) -> Self {
self.set_scale(scale);
self
}
/// Sets the alignment to use for this image.
pub fn set_alignment(&mut self, alignment: impl Into<Alignment>) {
self.alignment = alignment.into();
}
/// Sets the alignment to use for this image and returns it.
pub fn with_alignment(mut self, alignment: impl Into<Alignment>) -> Self {
self.set_alignment(alignment);
self
}
/// Determines the offset from left-side based on provided Alignment.
fn get_offset(&self, width: Mm, max_width: Mm) -> Position {
let horizontal_offset = match self.alignment {
Alignment::Left => Mm::default(),
Alignment::Center => (max_width - width) / 2.0,
Alignment::Right => max_width - width,
};
Position::new(horizontal_offset, 0)
}
/// Calculates a guess for the size of the image based on the dpi/pixel-count/scale.
fn get_size(&self) -> Size {
let mmpi: f64 = 25.4; // millimeters per inch
// Assume 300 DPI to be consistent with printpdf.
let dpi: f64 = self.dpi.unwrap_or(300.0);
let (px_width, px_height) = self.data.dimensions();
let (scale_width, scale_height): (f64, f64) = (self.scale.x, self.scale.y);
Size::new(
mmpi * ((scale_width * px_width as f64) / dpi),
mmpi * ((scale_height * px_height as f64) / dpi),
)
}
/// Sets the clockwise rotation of the image around the bottom left corner.
pub fn set_clockwise_rotation(&mut self, rotation: impl Into<Rotation>) {
self.rotation = rotation.into();
}
/// Sets the clockwise rotation of the image around the bottom left corner and then returns the
/// image.
pub fn with_clockwise_rotation(mut self, rotation: impl Into<Rotation>) -> Self {
self.set_clockwise_rotation(rotation);
self
}
/// Sets the expected DPI of the encoded image.
pub fn set_dpi(&mut self, dpi: f64) {
self.dpi = Some(dpi);
}
/// Sets the expected DPI of the encoded image and returns it.
pub fn with_dpi(mut self, dpi: f64) -> Self {
self.set_dpi(dpi);
self
}
}
impl Element for Image {
fn render(
&mut self,
_context: &Context,
area: render::Area<'_>,
_style: style::Style,
) -> Result<RenderResult, Error> {
let mut result = RenderResult::default();
let true_size = self.get_size();
let (bb_origin, bb_size) = bounding_box_offset_and_size(&self.rotation, &true_size);
let mut position: Position = if let Some(position) = self.position {
position
} else {
// Update the result size to be based on the bounding-box size/offset.
result.size = bb_size;
// No position override given; so we calculate the Alignment offset based on
// the area-size and width of the bounding box.
self.get_offset(bb_size.width, area.size().width)
};
// Fix the position with the bounding-box's origin which was changed from
// (0,0) when it was rotated in any way.
position += bb_origin;
// Insert/render the image with the overridden/calculated position.
area.add_image(&self.data, position, self.scale, self.rotation, self.dpi);
// Always false as we can't safely do this unless we want to try to do "sub-images".
// This is technically possible with the `image` package, but it is potentially more
// work than necessary. I'd rather support an "Auto-Scale" method to fit to area.
result.has_more = false;
Ok(result)
}
}
/// Given the Size of a box (width/height), compute the bounding-box size and offset when
/// rotated some degrees. The offset is the distance from the top-left corner of the bounding box
/// to the (originally) lower-left corner of the image.
#[allow(clippy::manual_range_contains)]
fn bounding_box_offset_and_size(rotation: &Rotation, size: &Size) -> (Position, Size) {
// alpha = rotation, beta = 90 - rotation
let alpha = rotation.degrees.to_radians();
let beta = (90.0 - rotation.degrees).to_radians();
// s* = sin of *
let sa = alpha.sin();
let sb = beta.sin();
// Bounding box calculation, based on
// https://math.stackexchange.com/questions/1628657/dimensions-of-a-rectangle-containing-a-rotated-rectangle
let width = (size.width.0 * sb).abs() + (size.height.0 * sa).abs();
let height = (size.height.0 * sb).abs() + (size.width.0 * sa).abs();
let bb_size = Size::new(width, height);
// Offset calculation -- to follow the calculations, consider the rotated rectangles, their
// bounding boxes and the triangles between them
let bb_position = if rotation.degrees < -180.0 {
unreachable!(
"Rotations must be in the range -180.0..=180.0, but got: {}",
rotation.degrees
);
} else if rotation.degrees <= -90.0 {
Position::new(size.width.0 * alpha.cos().abs(), 0)
} else if rotation.degrees <= 0.0 {
Position::new(0, size.height.0 * alpha.cos())
} else if rotation.degrees <= 90.0 {
Position::new(size.height.0 * beta.cos(), bb_size.height.0)
} else if rotation.degrees <= 180.0 {
Position::new(bb_size.width.0, size.width.0 * beta.cos())
} else {
unreachable!(
"Rotations must be in the range -180.0..=180.0, but got: {}",
rotation.degrees
);
};
(bb_position, bb_size)
}
#[cfg(test)]
mod tests {
use super::bounding_box_offset_and_size;
use crate::{Position, Rotation, Size};
use float_cmp::approx_eq;
macro_rules! assert_approx_eq {
($typ:ty, $lhs:expr, $rhs:expr) => {
let left = $lhs;
let right = $rhs;
assert!(
approx_eq!($typ, left, right, epsilon = 100.0 * f64::EPSILON, ulps = 10),
"assertion failed: `(left approx_eq right)`
left: `{:?}`,
right: `{:?}`",
left,
right
);
};
}
fn test_position(size: Size, rotation: f64, position: Position) {
println!("rotation = {}", rotation);
let rotation = Rotation::from(rotation);
assert_approx_eq!(
Position,
position,
bounding_box_offset_and_size(&rotation, &size).0
);
}
#[test]
fn test_bounding_box_size_square_0_deg() {
let size = Size::new(100, 100);
for rotation in &[-180.0, -90.0, 0.0, 90.0, 180.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(Size, size, bounding_box_offset_and_size(&rotation, &size).1);
}
}
#[test]
fn test_bounding_box_size_square_30_deg() {
let size = Size::new(100, 100);
let bb_width = (60.0f64.to_radians().sin() + 30.0f64.to_radians().sin()) * size.width.0;
let bb_size = Size::new(bb_width, bb_width);
for rotation in &[-150.0, -120.0, -30.0, -60.0, 30.0, 60.0, 120.0, 150.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(
Size,
bb_size,
bounding_box_offset_and_size(&rotation, &size).1
);
}
}
#[test]
fn test_bounding_box_size_square_45_deg() {
let size = Size::new(100, 100);
let bb_width = (2.0f64 * size.width.0.powf(2.0)).sqrt();
let bb_size = Size::new(bb_width, bb_width);
for rotation in &[-135.0, -45.0, 45.0, 135.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(
Size,
bb_size,
bounding_box_offset_and_size(&rotation, &size).1
);
}
}
#[test]
fn test_bounding_box_position_square_30_deg() {
let size = Size::new(100, 100);
let bb_width =
30.0f64.to_radians().sin() * size.width.0 + 60.0f64.to_radians().sin() * size.height.0;
let w30 = 30.0f64.to_radians().cos() * size.width.0;
let w60 = 60.0f64.to_radians().cos() * size.width.0;
test_position(size, -150.0, Position::new(w30, 0));
test_position(size, -120.0, Position::new(w60, 0));
test_position(size, -60.0, Position::new(0, w60));
test_position(size, -30.0, Position::new(0, w30));
test_position(size, 30.0, Position::new(w60, bb_width));
test_position(size, 60.0, Position::new(w30, bb_width));
test_position(size, 120.0, Position::new(bb_width, bb_width - w60));
test_position(size, 150.0, Position::new(bb_width, bb_width - w30));
}
#[test]
fn test_bounding_box_position_square_45_deg() {
let size = Size::new(100, 100);
let bb_width = (2.0f64 * size.width.0.powf(2.0)).sqrt();
test_position(size, -135.0, Position::new(bb_width / 2.0, 0));
test_position(size, -45.0, Position::new(0, bb_width / 2.0));
test_position(size, 45.0, Position::new(bb_width / 2.0, bb_width));
test_position(size, 135.0, Position::new(bb_width, bb_width / 2.0));
}
#[test]
fn test_bounding_box_position_square_90_deg() {
let size = Size::new(100, 100);
test_position(size, -180.0, Position::new(100, 0));
test_position(size, -90.0, Position::new(0, 0));
test_position(size, 0.0, Position::new(0, 100));
test_position(size, 90.0, Position::new(100, 100));
test_position(size, 180.0, Position::new(100, 0));
}
#[test]
fn test_bounding_box_size_rectangle_0_deg() {
let size = Size::new(200, 100);
for rotation in &[-180.0, 0.0, 180.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(Size, size, bounding_box_offset_and_size(&rotation, &size).1);
}
}
#[test]
fn test_bounding_box_size_rectangle_30_deg() {
let size = Size::new(200, 100);
let bb_width =
60.0f64.to_radians().sin() * size.width.0 + 30.0f64.to_radians().sin() * size.height.0;
let bb_height =
60.0f64.to_radians().sin() * size.height.0 + 30.0f64.to_radians().sin() * size.width.0;
let bb_size = Size::new(bb_width, bb_height);
for rotation in &[-150.0, -30.0, 30.0, 150.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(
Size,
bb_size,
bounding_box_offset_and_size(&rotation, &size).1
);
}
}
#[test]
fn test_bounding_box_size_rectangle_45_deg() {
let size = Size::new(200, 100);
let bb_width = 45.0f64.to_radians().sin() * (size.width.0 + size.height.0);
let bb_size = Size::new(bb_width, bb_width);
for rotation in &[-135.0, -45.0, 45.0, 135.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(
Size,
bb_size,
bounding_box_offset_and_size(&rotation, &size).1
);
}
}
#[test]
fn test_bounding_box_size_rectangle_60_deg() {
let size = Size::new(200, 100);
let bb_width =
30.0f64.to_radians().sin() * size.width.0 + 60.0f64.to_radians().sin() * size.height.0;
let bb_height =
30.0f64.to_radians().sin() * size.height.0 + 60.0f64.to_radians().sin() * size.width.0;
let bb_size = Size::new(bb_width, bb_height);
for rotation in &[-120.0, -60.0, 60.0, 120.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(
Size,
bb_size,
bounding_box_offset_and_size(&rotation, &size).1
);
}
}
#[test]
fn test_bounding_box_size_rectangle_90_deg() {
let size = Size::new(200, 100);
let bb_size = Size::new(100, 200);
for rotation in &[-90.0, 90.0] {
println!("rotation = {}", rotation);
let rotation = Rotation::from(*rotation);
assert_approx_eq!(
Size,
bb_size,
bounding_box_offset_and_size(&rotation, &size).1
);
}
}
#[test]
fn test_bounding_box_position_rectangle_30_deg() {
let size = Size::new(200, 100);
let bb_width =
30.0f64.to_radians().sin() * size.width.0 + 60.0f64.to_radians().sin() * size.height.0;
let bb_height =
30.0f64.to_radians().sin() * size.height.0 + 60.0f64.to_radians().sin() * size.width.0;
let h30 = 30.0f64.to_radians().cos() * size.height.0;
let h60 = 60.0f64.to_radians().cos() * size.height.0;
let w30 = 30.0f64.to_radians().cos() * size.width.0;
let w60 = 60.0f64.to_radians().cos() * size.width.0;
test_position(size, -150.0, Position::new(w30, 0));
test_position(size, -120.0, Position::new(w60, 0));
test_position(size, -60.0, Position::new(0, h60));
test_position(size, -30.0, Position::new(0, h30));
test_position(size, 30.0, Position::new(h60, bb_width));
test_position(size, 60.0, Position::new(h30, bb_height));
test_position(size, 120.0, Position::new(bb_width, bb_height - h60));
test_position(size, 150.0, Position::new(bb_height, bb_width - h30));
}
#[test]
fn test_bounding_box_position_rectangle_45_deg() {
let size = Size::new(200, 100);
let bb_width = 45.0f64.to_radians().sin() * (size.width.0 + size.height.0);
test_position(size, -135.0, Position::new(2.0 * bb_width / 3.0, 0));
test_position(size, -45.0, Position::new(0, bb_width / 3.0));
test_position(size, 45.0, Position::new(bb_width / 3.0, bb_width));
test_position(size, 135.0, Position::new(bb_width, 2.0 * bb_width / 3.0));
}
#[test]
fn test_bounding_box_position_rectangle_90_deg() {
let size = Size::new(200, 100);
test_position(size, -180.0, Position::new(200, 0));
test_position(size, -90.0, Position::new(0, 0));
test_position(size, 0.0, Position::new(0, 100));
test_position(size, 90.0, Position::new(100, 200));
test_position(size, 180.0, Position::new(200, 0));
}
}
+163
View File
@@ -0,0 +1,163 @@
// SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Error types for `genpdf`.
use std::error;
use std::fmt;
use std::io;
/// Helper trait for creating [`Error`][] instances.
///
/// This trait is inspired by [`anyhow::Context`][].
///
/// [`Error`]: struct.Error.html
/// [`anyhow::Context`]: https://docs.rs/anyhow/latest/anyhow/trait.Context.html
pub trait Context<T> {
/// Maps the error to an [`Error`][] instance with the given message.
///
/// [`Error`]: struct.Error.html
fn context(self, msg: impl Into<String>) -> Result<T, Error>;
/// Maps the error to an [`Error`][] instance message produced by the given callback.
///
/// [`Error`]: struct.Error.html
fn with_context<F, S>(self, cb: F) -> Result<T, Error>
where
F: Fn() -> S,
S: Into<String>;
}
impl<T, E: Into<ErrorKind>> Context<T> for Result<T, E> {
fn context(self, msg: impl Into<String>) -> Result<T, Error> {
self.map_err(|err| Error::new(msg, err))
}
fn with_context<F, S>(self, cb: F) -> Result<T, Error>
where
F: Fn() -> S,
S: Into<String>,
{
self.map_err(move |err| Error::new(cb(), err))
}
}
/// An error that occured in a `genpdf` function.
///
/// The error consists of an error message (provided by the `Display` implementation) and an error
/// kind, see [`kind`](#method.kind).
#[derive(Debug)]
pub struct Error {
msg: String,
kind: ErrorKind,
}
impl Error {
/// Creates a new error.
pub fn new(msg: impl Into<String>, kind: impl Into<ErrorKind>) -> Error {
Error {
msg: msg.into(),
kind: kind.into(),
}
}
/// Returns the error kind for this error.
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self.kind {
ErrorKind::Internal => None,
ErrorKind::InvalidData => None,
ErrorKind::InvalidFont => None,
ErrorKind::PageSizeExceeded => None,
ErrorKind::UnsupportedEncoding => None,
ErrorKind::IoError(err) => Some(err),
ErrorKind::PdfError(err) => Some(err),
ErrorKind::PdfIndexError(err) => Some(err),
ErrorKind::RusttypeError(err) => Some(err),
#[cfg(feature = "images")]
ErrorKind::ImageError(err) => Some(err),
}
}
}
/// The kind of an [`Error`](struct.Error.html).
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
/// An internal error.
Internal,
/// An error caused by invalid data.
InvalidData,
/// An error caused by an invalid font.
InvalidFont,
/// An element exceeds the page size and could not be printed.
PageSizeExceeded,
/// A string with unsupported characters was used with a built-in font.
UnsupportedEncoding,
/// An IO error.
IoError(io::Error),
/// An error caused by invalid data in `printpdf`.
PdfError(printpdf::PdfError),
/// An error caused by an invalid index in `printpdf`.
PdfIndexError(printpdf::IndexError),
/// An error caused by `rusttype`.
RusttypeError(rusttype::Error),
/// An error caused by `image`.
///
/// *Only available if the `images` feature is enabled.*
#[cfg(feature = "images")]
ImageError(image::ImageError),
}
impl From<io::Error> for ErrorKind {
fn from(error: io::Error) -> ErrorKind {
ErrorKind::IoError(error)
}
}
impl From<printpdf::Error> for ErrorKind {
fn from(error: printpdf::Error) -> ErrorKind {
match error {
printpdf::Error::Io(err) => err.into(),
printpdf::Error::Rusttype(err) => err.into(),
printpdf::Error::Pdf(err) => err.into(),
printpdf::Error::Index(err) => err.into(),
}
}
}
impl From<printpdf::IndexError> for ErrorKind {
fn from(error: printpdf::IndexError) -> ErrorKind {
ErrorKind::PdfIndexError(error)
}
}
impl From<printpdf::PdfError> for ErrorKind {
fn from(error: printpdf::PdfError) -> ErrorKind {
ErrorKind::PdfError(error)
}
}
impl From<rusttype::Error> for ErrorKind {
fn from(error: rusttype::Error) -> ErrorKind {
ErrorKind::RusttypeError(error)
}
}
#[cfg(feature = "images")]
impl From<image::ImageError> for ErrorKind {
fn from(error: image::ImageError) -> ErrorKind {
ErrorKind::ImageError(error)
}
}
+490
View File
@@ -0,0 +1,490 @@
// SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Fonts, font families and a font cache.
//!
//! Before you can use a font in a PDF document, you have to load the [`FontData`][] for it, either
//! from a file ([`FontData::load`][]) or from bytes ([`FontData::new`][]). See the [`rusttype`][]
//! crate for the supported data formats. Use the [`from_files`][] function to load a font family
//! from a set of files following the default naming conventions.
//!
//! The [`FontCache`][] caches all loaded fonts. A [`Font`][] is a reference to a cached font in
//! the [`FontCache`][]. A [`FontFamily`][] is a collection of a regular, a bold, an italic and a
//! bold italic font (raw data or cached).
//!
//! Add fonts to a document’s font cache by calling [`Document::add_font_family`][]. This method
//! returns a reference to the cached data that you then can use with the [`Style`][] struct to
//! change the font family of an element.
//!
//! There are two methods for using fonts in a PDF font: You can either embed the font data into
//! the PDF file. Or you can use one of the three built-in font families ([`Builtin`][]) that PDF
//! viewers are expected to support. You can choose between the two methods when loading the font
//! ([`from_files`][], [`FontData::load`][], [`FontData::new`][]).
//!
//! If you choose a built-in font family, you still have to provide the font data so that `genpdf`
//! has access to its glyph metrics. Note that it is sufficient to use a font that is metrically
//! identical to the built-in font. For example, you can use the Liberation fonts instad of the
//! proprietary Helvetica, Times and Courier fonts.
//!
//! Built-in fonts can only be used with characters that are supported by the [Windows-1252][]
//! encoding.
//!
//! **Note:** The [`Font`][] and [`FontFamily<Font>`][`FontFamily`] structs are only valid for the
//! [`FontCache`][] they have been created with. If you dont use the low-level [`render`][] module
//! directly, only use the [`Document::add_font_family`][] method to add fonts!
//!
//! # Internals
//!
//! There are two types of font data: A [`FontData`][] instance stores information about the glyph
//! metrics that is used to calculate the text size. It can be loaded at any time using the
//! [`FontData::load`][] and [`FontData::new`][] methods. Once the PDF document is rendered, a
//! [`printpdf::IndirectFontRef`][] is used to draw text in the PDF document. Before a font can be
//! used in a PDF document, it has to be embedded using the [`FontCache::load_pdf_fonts`][] method.
//!
//! If you use the high-level interface provided by [`Document`][] to generate a PDF document, these
//! steps are done automatically. You only have to manually populate the font cache if you use the
//! low-level interface in the [`render`][] module.
//!
//! [`render`]: ../render/
//! [`Document`]: ../struct.Document.html
//! [`Document::add_font_family`]: ../struct.Document.html#method.add_font_family
//! [`Style`]: ../style/struct.Style.html
//! [`from_files`]: fn.from_files.html
//! [`Builtin`]: enum.Builtin.html
//! [`FontCache`]: struct.FontCache.html
//! [`FontCache::load_pdf_fonts`]: struct.FontCache.html#method.load_pdf_fonts
//! [`FontData`]: struct.FontData.html
//! [`FontData::new`]: struct.FontData.html#method.new
//! [`FontData::load`]: struct.FontData.html#method.load
//! [`Font`]: struct.Font.html
//! [`FontFamily`]: struct.FontFamily.html
//! [`rusttype`]: https://docs.rs/rusttype
//! [`rusttype::Font`]: https://docs.rs/rusttype/0.8.3/rusttype/struct.Font.html
//! [`printpdf`]: https://docs.rs/printpdf
//! [`printpdf::IndirectFontRef`]: https://docs.rs/printpdf/0.3.2/printpdf/types/plugins/graphics/two_dimensional/font/struct.IndirectFontRef.html
//! [Windows-1252]: https://en.wikipedia.org/wiki/Windows-1252
use std::fmt;
use std::fs;
use std::path;
use crate::error::{Context as _, Error, ErrorKind};
use crate::render;
use crate::style::Style;
use crate::Mm;
/// Stores font data that can be referenced by a [`Font`][] or [`FontFamily`][].
///
/// If you use the high-level interface provided by [`Document`][], you don’t have to access this
/// type. See the [module documentation](index.html) for details on the internals.
///
/// [`Document`]: ../struct.Document.html
/// [`Font`]: struct.Font.html
/// [`FontFamily`]: struct.FontFamily.html
#[derive(Debug)]
pub struct FontCache {
fonts: Vec<FontData>,
pdf_fonts: Vec<printpdf::IndirectFontRef>,
// We have to use an option because we first have to construct the FontCache before we can load
// a font, but the default font is always loaded in new, so this options is always some
// (outside of new).
default_font_family: Option<FontFamily<Font>>,
}
impl FontCache {
/// Creates a new font cache with the given default font family.
pub fn new(default_font_family: FontFamily<FontData>) -> FontCache {
let mut font_cache = FontCache {
fonts: Vec::new(),
pdf_fonts: Vec::new(),
default_font_family: None,
};
font_cache.default_font_family = Some(font_cache.add_font_family(default_font_family));
font_cache
}
/// Adds the given font to the cache and returns a reference to it.
pub fn add_font(&mut self, font_data: FontData) -> Font {
let is_builtin = match &font_data.raw_data {
RawFontData::Builtin(_) => true,
RawFontData::Embedded(_) => false,
};
let font = Font::new(self.fonts.len(), is_builtin, &font_data.rt_font);
self.fonts.push(font_data);
font
}
/// Adds the given font family to the cache and returns a reference to it.
pub fn add_font_family(&mut self, family: FontFamily<FontData>) -> FontFamily<Font> {
FontFamily {
regular: self.add_font(family.regular),
bold: self.add_font(family.bold),
italic: self.add_font(family.italic),
bold_italic: self.add_font(family.bold_italic),
}
}
/// Embeds all loaded fonts into the document generated by the given renderer and caches a
/// reference to them.
pub fn load_pdf_fonts(&mut self, renderer: &render::Renderer) -> Result<(), Error> {
self.pdf_fonts.clear();
for font in &self.fonts {
let pdf_font = match &font.raw_data {
RawFontData::Builtin(builtin) => renderer.add_builtin_font(*builtin)?,
RawFontData::Embedded(data) => renderer.add_embedded_font(&data)?,
};
self.pdf_fonts.push(pdf_font);
}
Ok(())
}
/// Returns the default font family for this font cache.
pub fn default_font_family(&self) -> FontFamily<Font> {
self.default_font_family
.expect("Invariant violated: no default font family for FontCache")
}
/// Returns a reference to the emebdded PDF font for the given font, if available.
///
/// This method may only be called with [`Font`][] instances that have been created by this
/// font cache. PDF fonts are only avaiable if [`load_pdf_fonts`][] has been called.
///
/// [`Font`]: struct.Font.html
/// [`load_pdf_fonts`]: #method.load_pdf_fonts
pub fn get_pdf_font(&self, font: Font) -> Option<&printpdf::IndirectFontRef> {
self.pdf_fonts.get(font.idx)
}
/// Returns a reference to the Rusttype font for the given font, if available.
///
/// This method may only be called with [`Font`][] instances that have been created by this
/// font cache.
///
/// [`Font`]: struct.Font.html
pub fn get_rt_font(&self, font: Font) -> &rusttype::Font<'static> {
&self.fonts[font.idx].rt_font
}
}
/// The data for a font that is cached by a [`FontCache`][].
///
/// [`FontCache`]: struct.FontCache.html
#[derive(Clone, Debug)]
pub struct FontData {
rt_font: rusttype::Font<'static>,
raw_data: RawFontData,
}
impl FontData {
/// Loads a font from the given data.
///
/// The provided data must by readable by [`rusttype`][]. If `builtin` is set, a built-in PDF
/// font is used instead of embedding the font in the PDF file (see the [module
/// documentation](index.html) for more information). In this case, the given font must be
/// metrically identical to the built-in font.
///
/// [`rusttype`]: https://docs.rs/rusttype
pub fn new(data: Vec<u8>, builtin: Option<printpdf::BuiltinFont>) -> Result<FontData, Error> {
let raw_data = if let Some(builtin) = builtin {
RawFontData::Builtin(builtin)
} else {
RawFontData::Embedded(data.clone())
};
let rt_font = rusttype::Font::from_bytes(data).context("Failed to read rusttype font")?;
if rt_font.units_per_em() == 0 {
Err(Error::new(
"The font is not scalable",
ErrorKind::InvalidFont,
))
} else {
Ok(FontData { rt_font, raw_data })
}
}
/// Loads the font at the given path.
///
/// The path must point to a file that can be read by [`rusttype`][]. If `builtin` is set, a
/// built-in PDF font is used instead of embedding the font in the PDF file (see the [module
/// documentation](index.html) for more information). In this case, the given font must be
/// metrically identical to the built-in font.
///
/// [`rusttype`]: https://docs.rs/rusttype
pub fn load(
path: impl AsRef<path::Path>,
builtin: Option<printpdf::BuiltinFont>,
) -> Result<FontData, Error> {
let data = fs::read(path.as_ref())
.with_context(|| format!("Failed to open font file {}", path.as_ref().display()))?;
FontData::new(data, builtin)
}
}
#[derive(Clone, Debug)]
enum RawFontData {
Builtin(printpdf::BuiltinFont),
Embedded(Vec<u8>),
}
#[derive(Clone, Copy, Debug)]
enum FontStyle {
Regular,
Bold,
Italic,
BoldItalic,
}
impl FontStyle {
fn name(&self) -> &'static str {
match self {
FontStyle::Regular => "Regular",
FontStyle::Bold => "Bold",
FontStyle::Italic => "Italic",
FontStyle::BoldItalic => "BoldItalic",
}
}
}
impl fmt::Display for FontStyle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// A built-in font family.
///
/// A PDF viewer typically supports three font families that don’t have to be embedded into the PDF
/// file: Times, Helvetica and Courier.
///
/// See the [module documentation](index.html) for more information.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Builtin {
/// The Times font family.
Times,
/// The Helvetica font family.
Helvetica,
/// The Courier font family.
Courier,
}
impl Builtin {
fn style(&self, style: FontStyle) -> printpdf::BuiltinFont {
match self {
Builtin::Times => match style {
FontStyle::Regular => printpdf::BuiltinFont::TimesRoman,
FontStyle::Bold => printpdf::BuiltinFont::TimesBold,
FontStyle::Italic => printpdf::BuiltinFont::TimesItalic,
FontStyle::BoldItalic => printpdf::BuiltinFont::TimesBoldItalic,
},
Builtin::Helvetica => match style {
FontStyle::Regular => printpdf::BuiltinFont::Helvetica,
FontStyle::Bold => printpdf::BuiltinFont::HelveticaBold,
FontStyle::Italic => printpdf::BuiltinFont::HelveticaOblique,
FontStyle::BoldItalic => printpdf::BuiltinFont::HelveticaBoldOblique,
},
Builtin::Courier => match style {
FontStyle::Regular => printpdf::BuiltinFont::Courier,
FontStyle::Bold => printpdf::BuiltinFont::CourierBold,
FontStyle::Italic => printpdf::BuiltinFont::CourierOblique,
FontStyle::BoldItalic => printpdf::BuiltinFont::CourierBoldOblique,
},
}
}
}
/// A collection of fonts with different styles.
///
/// See the [module documentation](index.html) for details on the internals.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontFamily<T: Clone + fmt::Debug> {
/// The regular variant of this font family.
pub regular: T,
/// The bold variant of this font family.
pub bold: T,
/// The italic variant of this font family.
pub italic: T,
/// The bold italic variant of this font family.
pub bold_italic: T,
}
impl<T: Clone + Copy + fmt::Debug + PartialEq> FontFamily<T> {
/// Returns the font for the given style.
pub fn get(&self, style: Style) -> T {
if style.is_bold() && style.is_italic() {
self.bold_italic
} else if style.is_bold() {
self.bold
} else if style.is_italic() {
self.italic
} else {
self.regular
}
}
}
/// A reference to a font cached by a [`FontCache`][].
///
/// See the [module documentation](index.html) for details on the internals.
///
/// [`FontCache`]: struct.FontCache.html
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Font {
idx: usize,
is_builtin: bool,
scale: rusttype::Scale,
line_height: Mm,
glyph_height: Mm,
}
impl Font {
fn new(idx: usize, is_builtin: bool, rt_font: &rusttype::Font<'static>) -> Font {
let units_per_em = rt_font.units_per_em();
assert!(units_per_em != 0);
let units_per_em = f32::from(units_per_em);
let v_metrics = rt_font.v_metrics_unscaled();
let glyph_height = (v_metrics.ascent - v_metrics.descent) / units_per_em;
let scale = rusttype::Scale::uniform(glyph_height);
let line_height = glyph_height + v_metrics.line_gap / units_per_em;
Font {
idx,
is_builtin,
scale,
line_height: printpdf::Pt(f64::from(line_height)).into(),
glyph_height: printpdf::Pt(f64::from(glyph_height)).into(),
}
}
/// Returns whether this font is a built-in PDF font.
pub fn is_builtin(&self) -> bool {
self.is_builtin
}
/// Returns the line height for text with this font and the given font size.
pub fn get_line_height(&self, font_size: u8) -> Mm {
self.line_height * f64::from(font_size)
}
/// Returns the glyph height for text with this font and the given font size.
pub fn glyph_height(&self, font_size: u8) -> Mm {
self.glyph_height * f64::from(font_size)
}
/// Returns the width of a character with this font and the given font size.
///
/// The given [`FontCache`][] must be the font cache that loaded this font.
///
/// [`FontCache`]: struct.FontCache.html
pub fn char_width(&self, font_cache: &FontCache, c: char, font_size: u8) -> Mm {
let advance_width = font_cache
.get_rt_font(*self)
.glyph(c)
.scaled(self.scale)
.h_metrics()
.advance_width;
Mm::from(printpdf::Pt(f64::from(
advance_width * f32::from(font_size),
)))
}
/// Returns the width of a string with this font and the given font size.
///
/// The given [`FontCache`][] must be the font cache that loaded this font.
///
/// [`FontCache`]: struct.FontCache.html
pub fn str_width(&self, font_cache: &FontCache, s: &str, font_size: u8) -> Mm {
let str_width: Mm = font_cache
.get_rt_font(*self)
.glyphs_for(s.chars())
.map(|g| g.scaled(self.scale).h_metrics().advance_width)
.map(|w| Mm::from(printpdf::Pt(f64::from(w * f32::from(font_size)))))
.sum();
let kerning_width: Mm = self
.kerning(font_cache, s.chars())
.into_iter()
.map(|val| val * f32::from(font_size))
.map(|val| Mm::from(printpdf::Pt(f64::from(val))))
.sum();
str_width + kerning_width
}
/// Returns the kerning data for the given sequence of characters.
///
/// The *i*-th value of the returned data is the amount of kerning to insert before the *i*-th
/// character of the sequence.
///
/// The given [`FontCache`][] must be the font cache that loaded this font.
///
/// [`FontCache`]: struct.FontCache.html
pub fn kerning<I>(&self, font_cache: &FontCache, iter: I) -> Vec<f32>
where
I: IntoIterator<Item = char>,
{
let font = font_cache.get_rt_font(*self);
font.glyphs_for(iter.into_iter())
.scan(None, |last, g| {
let pos = if let Some(last) = last {
Some(font.pair_kerning(self.scale, *last, g.id()))
} else {
Some(0.0)
};
*last = Some(g.id());
pos
})
.collect()
}
/// Returns the glyphs IDs for the given sequence of characters.
///
/// The given [`FontCache`][] must be the font cache that loaded this font.
///
/// [`FontCache`]: struct.FontCache.html
pub fn glyph_ids<I>(&self, font_cache: &FontCache, iter: I) -> Vec<u16>
where
I: IntoIterator<Item = char>,
{
let font = font_cache.get_rt_font(*self);
font.glyphs_for(iter.into_iter())
.map(|g| g.id().0 as u16)
.collect()
}
}
fn from_file(
dir: impl AsRef<path::Path>,
name: &str,
style: FontStyle,
builtin: Option<Builtin>,
) -> Result<FontData, Error> {
let builtin = builtin.map(|b| b.style(style));
FontData::load(
&dir.as_ref().join(format!("{}-{}.ttf", name, style)),
builtin,
)
}
/// Loads the font family at the given path with the given name.
///
/// This method assumes that at the given path, these files exist and are valid font files:
/// - `{name}-Regular.ttf`
/// - `{name}-Bold.ttf`
/// - `{name}-Italic.ttf`
/// - `{name}-BoldItalic.ttf`
///
/// If `builtin` is set, built-in PDF fonts are used instead of embedding the fonts in the PDF file
/// (see the [module documentation](index.html) for more information). In this case, the given
/// fonts must be metrically identical to the built-in fonts.
pub fn from_files(
dir: impl AsRef<path::Path>,
name: &str,
builtin: Option<Builtin>,
) -> Result<FontFamily<FontData>, Error> {
let dir = dir.as_ref();
Ok(FontFamily {
regular: from_file(dir, name, FontStyle::Regular, builtin)?,
bold: from_file(dir, name, FontStyle::Bold, builtin)?,
italic: from_file(dir, name, FontStyle::Italic, builtin)?,
bold_italic: from_file(dir, name, FontStyle::BoldItalic, builtin)?,
})
}
+1015
View File
File diff suppressed because it is too large. Load diff
+588
View File
@@ -0,0 +1,588 @@
// SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Low-level PDF rendering utilities.
//!
//! This module provides low-level abstractions over [`printpdf`][]: A [`Renderer`][] creates a
//! document with one or more pages with different sizes. A [`Page`][] has one or more layers, all
//! of the same size. A [`Layer`][] can be used to access its [`Area`][].
//!
//! An [`Area`][] is a view on a full layer or on a part of a layer. It can be used to print
//! lines and text. For more advanced text formatting, you can create a [`TextSection`][] from an
//! [`Area`][].
//!
//! [`printpdf`]: https://docs.rs/printpdf/latest/printpdf
//! [`Renderer`]: struct.Renderer.html
//! [`Page`]: struct.Page.html
//! [`Layer`]: struct.Layer.html
//! [`Area`]: struct.Area.html
//! [`TextSection`]: struct.TextSection.html
use std::io;
use crate::error::{Context as _, Error, ErrorKind};
use crate::fonts;
use crate::style::{Color, Style};
use crate::{Margins, Mm, Position, Size};
#[cfg(feature = "images")]
use crate::{Rotation, Scale};
/// Renders a PDF document with one or more pages.
///
/// This is a wrapper around a [`printpdf::PdfDocumentReference`][].
///
/// [`printpdf::PdfDocumentReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_document/struct.PdfDocumentReference.html
pub struct Renderer {
doc: printpdf::PdfDocumentReference,
// invariant: pages.len() >= 1
pages: Vec<Page>,
}
impl Renderer {
/// Creates a new PDF document renderer with one page of the given size and the given title.
pub fn new(size: impl Into<Size>, title: impl AsRef<str>) -> Result<Renderer, Error> {
let size = size.into();
let (doc, page_idx, layer_idx) = printpdf::PdfDocument::new(
title.as_ref(),
size.width.into(),
size.height.into(),
"Layer 1",
);
let page_ref = doc.get_page(page_idx);
let layer_ref = page_ref.get_layer(layer_idx);
let page = Page::new(page_ref, layer_ref, size);
Ok(Renderer {
doc,
pages: vec![page],
})
}
/// Sets the PDF conformance for the generated PDF document.
pub fn with_conformance(mut self, conformance: printpdf::PdfConformance) -> Self {
self.doc = self.doc.with_conformance(conformance);
self
}
/// Adds a new page with the given size to the document.
pub fn add_page(&mut self, size: impl Into<Size>) {
let size = size.into();
let (page_idx, layer_idx) =
self.doc
.add_page(size.width.into(), size.height.into(), "Layer 1");
let page_ref = self.doc.get_page(page_idx);
let layer_ref = page_ref.get_layer(layer_idx);
self.pages.push(Page::new(page_ref, layer_ref, size))
}
/// Returns the number of pages in this document.
pub fn page_count(&self) -> usize {
self.pages.len()
}
/// Returns a page of this document.
pub fn get_page(&self, idx: usize) -> Option<&Page> {
self.pages.get(idx)
}
/// Returns a mutable reference to a page of this document.
pub fn get_page_mut(&mut self, idx: usize) -> Option<&mut Page> {
self.pages.get_mut(idx)
}
/// Returns a mutable reference to the first page of this document.
pub fn first_page(&self) -> &Page {
&self.pages[0]
}
/// Returns the first page of this document.
pub fn first_page_mut(&mut self) -> &mut Page {
&mut self.pages[0]
}
/// Returns the last page of this document.
pub fn last_page(&self) -> &Page {
&self.pages[self.pages.len() - 1]
}
/// Returns a mutable reference to the last page of this document.
pub fn last_page_mut(&mut self) -> &mut Page {
let idx = self.pages.len() - 1;
&mut self.pages[idx]
}
/// Loads the font from the given data, adds it to the generated document and returns a
/// reference to it.
pub fn add_builtin_font(
&self,
builtin: printpdf::BuiltinFont,
) -> Result<printpdf::IndirectFontRef, Error> {
self.doc
.add_builtin_font(builtin)
.context("Failed to load PDF font")
}
/// Loads the font from the given data, adds it to the generated document and returns a
/// reference to it.
pub fn add_embedded_font(&self, data: &[u8]) -> Result<printpdf::IndirectFontRef, Error> {
self.doc
.add_external_font(data)
.context("Failed to load PDF font")
}
/// Writes this PDF document to a writer.
pub fn write(self, w: impl io::Write) -> Result<(), Error> {
self.doc
.save(&mut io::BufWriter::new(w))
.context("Failed to save document")
}
}
/// A page of a PDF document.
///
/// This is a wrapper around a [`printpdf::PdfPageReference`][].
///
/// [`printpdf::PdfPageReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_page/struct.PdfPageReference.html
pub struct Page {
page: printpdf::PdfPageReference,
size: Size,
// invariant: layers.len() >= 1
layers: Vec<Layer>,
}
impl Page {
fn new(
page: printpdf::PdfPageReference,
layer: printpdf::PdfLayerReference,
size: Size,
) -> Page {
Page {
page,
size,
layers: vec![Layer::new(layer, size)],
}
}
/// Adds a new layer with the given name to the page.
pub fn add_layer(&mut self, name: impl Into<String>) {
let layer = self.page.add_layer(name);
self.layers.push(Layer::new(layer, self.size));
}
/// Returns the number of layers on this page.
pub fn layer_count(&self) -> usize {
self.layers.len()
}
/// Returns a layer of this page.
pub fn get_layer(&self, idx: usize) -> Option<&Layer> {
self.layers.get(idx)
}
/// Returns the first layer of this page.
pub fn first_layer(&self) -> &Layer {
&self.layers[0]
}
/// Returns the last layer of this page.
pub fn last_layer(&self) -> &Layer {
&self.layers[self.layers.len() - 1]
}
}
/// A layer of a page of a PDF document.
///
/// This is a wrapper around a [`printpdf::PdfLayerReference`][].
///
/// [`printpdf::PdfLayerReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_layer/struct.PdfLayerReference.html
pub struct Layer {
layer: printpdf::PdfLayerReference,
size: Size,
}
impl Layer {
fn new(layer: printpdf::PdfLayerReference, size: Size) -> Layer {
Layer { layer, size }
}
/// Returns a drawable area for this layer.
pub fn area(&self) -> Area<'_> {
Area::new(self, Position::default(), self.size)
}
/// Transforms the given position that is relative to the upper left corner of the layer to a
/// position that is relative to the lower left corner of the layer (as used by `printpdf`).
fn transform_position(&self, mut position: Position) -> Position {
position.y = self.size.height - position.y;
position
}
}
/// A view on an area of a PDF layer that can be drawn on.
///
/// This struct provides access to the drawing methods of a [`printpdf::PdfLayerReference`][]. It
/// is defined by the layer that is drawn on and the origin and the size of the area.
///
/// [`printpdf::PdfLayerReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_layer/struct.PdfLayerReference.html
#[derive(Clone)]
pub struct Area<'a> {
layer: &'a Layer,
origin: Position,
size: Size,
}
impl<'a> Area<'a> {
fn new(layer: &'a Layer, origin: Position, size: Size) -> Area<'a> {
Area {
layer,
origin,
size,
}
}
/// Reduces the size of the drawable area by the given margins.
pub fn add_margins(&mut self, margins: impl Into<Margins>) {
let margins = margins.into();
self.origin.x += margins.left;
self.origin.y += margins.top;
self.size.width -= margins.left + margins.right;
self.size.height -= margins.top + margins.bottom;
}
/// Returns the size of this area.
pub fn size(&self) -> Size {
self.size
}
/// Adds the given offset to the area, reducing the drawable area.
pub fn add_offset(&mut self, offset: impl Into<Position>) {
let offset = offset.into();
self.origin.x += offset.x;
self.origin.y += offset.y;
self.size.width -= offset.x;
self.size.height -= offset.y;
}
/// Sets the size of this area.
pub fn set_size(&mut self, size: impl Into<Size>) {
self.size = size.into();
}
/// Sets the width of this area.
pub fn set_width(&mut self, width: Mm) {
self.size.width = width;
}
/// Sets the height of this area.
pub fn set_height(&mut self, height: Mm) {
self.size.height = height;
}
/// Splits this area horizontally using the given weights.
///
/// The returned vector has the same number of elements as the provided slice. The width of
/// the *i*-th area is *width \* weights[i] / total_weight*, where *width* is the width of this
/// area, and *total_weight* is the sum of all given weights.
pub fn split_horizontally(&self, weights: &[usize]) -> Vec<Area<'a>> {
let total_weight: usize = weights.iter().sum();
let factor = self.size.width / total_weight as f64;
let widths = weights.iter().map(|weight| factor * *weight as f64);
let mut offset = Mm(0.0);
let mut areas = Vec::new();
for width in widths {
let mut area = self.clone();
area.origin.x += offset;
area.size.width = width;
areas.push(area);
offset += width;
}
areas
}
/// Inserts an image into the document.
///
/// *Only available if the `images` feature is enabled.*
///
/// The position is assumed to be relative to the upper left hand corner of the area.
/// Your position will need to compensate for rotation/scale/dpi. Using [`Image`][]’s
/// render functionality will do this for you and is the recommended way to
/// insert an image into an Area.
///
/// [`Image`]: ../elements/struct.Image.html
#[cfg(feature = "images")]
pub fn add_image(
&self,
image: &image::DynamicImage,
position: Position,
scale: Scale,
rotation: Rotation,
dpi: Option<f64>,
) {
let dynamic_image = printpdf::Image::from_dynamic_image(image);
let real_position = self.transform_position(position);
let layer = self.layer().clone();
dynamic_image.add_to_layer(
layer,
Some(real_position.x.into()),
Some(real_position.y.into()),
rotation.into(),
Some(scale.x),
Some(scale.y),
dpi,
);
}
/// Draws a line with the given points and the given style.
///
/// Currently, this method only uses the color of the given style as the outline color (if set).
/// The points are relative to the upper left corner of the area.
pub fn draw_line(&self, points: Vec<Position>, style: Style) {
let line_points: Vec<_> = points
.into_iter()
.map(|pos| (self.transform_position(pos).into(), false))
.collect();
let line = printpdf::Line {
points: line_points,
is_closed: false,
has_fill: false,
has_stroke: true,
is_clipping_path: false,
};
if let Some(color) = style.color() {
self.layer().set_outline_color(color.into());
}
self.layer().add_shape(line);
if style.color().is_some() {
self.layer().set_outline_color(Color::Rgb(0, 0, 0).into());
}
}
/// Draws an axis-aligned rectangle outline.
///
/// The position is relative to the upper left corner of the area.
pub fn draw_rect(&self, position: Position, size: Size, style: Style) {
self.draw_rectangle(position, size, style, false, true);
}
/// Draws a filled axis-aligned rectangle.
///
/// The position is relative to the upper left corner of the area.
pub fn fill_rect(&self, position: Position, size: Size, style: Style) {
self.draw_rectangle(position, size, style, true, false);
}
fn draw_rectangle(
&self,
position: Position,
size: Size,
style: Style,
fill: bool,
stroke: bool,
) {
let points = vec![
position,
Position::new(position.x + size.width, position.y),
Position::new(position.x + size.width, position.y + size.height),
Position::new(position.x, position.y + size.height),
];
let line_points: Vec<_> = points
.into_iter()
.map(|pos| (self.transform_position(pos).into(), false))
.collect();
let line = printpdf::Line {
points: line_points,
is_closed: true,
has_fill: fill,
has_stroke: stroke,
is_clipping_path: false,
};
if let Some(color) = style.color() {
if fill {
self.layer().set_fill_color(color.into());
}
if stroke {
self.layer().set_outline_color(color.into());
}
}
self.layer().add_shape(line);
if style.color().is_some() {
if fill {
self.layer().set_fill_color(Color::Rgb(0, 0, 0).into());
}
if stroke {
self.layer().set_outline_color(Color::Rgb(0, 0, 0).into());
}
}
}
/// Tries to draw the given string at the given position and returns `true` if the area was
/// large enough to draw the string.
///
/// The font cache must contain the PDF font for the font set in the style. The position is
/// relative to the upper left corner of the area.
pub fn print_str<S: AsRef<str>>(
&self,
font_cache: &fonts::FontCache,
position: Position,
style: Style,
s: S,
) -> Result<bool, Error> {
if let Some(mut section) = self.text_section(font_cache, position, style) {
section.print_str(s, style)?;
Ok(true)
} else {
Ok(false)
}
}
/// Creates a new text section at the given position if the text section fits in this area.
///
/// The given style is only used to calculate the line height of the section. The position is
/// relative to the upper left corner of the area. The font cache must contain the PDF font
/// for all fonts printed with the text section.
pub fn text_section<'f>(
&self,
font_cache: &'f fonts::FontCache,
position: Position,
style: Style,
) -> Option<TextSection<'_, 'f, 'a>> {
TextSection::new(font_cache, self, position, style)
}
/// Transforms the given position that is relative to the upper left corner of the area to a
/// position that is relative to the lower left corner of its layer (as used by `printpdf`).
fn transform_position(&self, mut position: Position) -> Position {
position += self.origin;
self.layer.transform_position(position)
}
fn layer(&self) -> &printpdf::PdfLayerReference {
&self.layer.layer
}
}
/// A text section that is drawn on an area of a PDF layer.
pub struct TextSection<'a, 'f, 'l> {
font_cache: &'f fonts::FontCache,
area: &'a Area<'l>,
line_height: Mm,
cursor: Position,
fill_color: Option<Color>,
}
impl<'a, 'f, 'l> TextSection<'a, 'f, 'l> {
fn new(
font_cache: &'f fonts::FontCache,
area: &'a Area<'l>,
position: Position,
style: Style,
) -> Option<TextSection<'a, 'f, 'l>> {
let height = style.font(font_cache).glyph_height(style.font_size());
if position.y + height > area.size.height {
return None;
}
let line_height = style.line_height(font_cache);
let section = TextSection {
font_cache,
area,
line_height,
cursor: position,
fill_color: None,
};
section.layer().begin_text_section();
section.layer().set_line_height(line_height.into());
let cursor = area.transform_position(position);
section
.layer()
.set_text_cursor(cursor.x.into(), (cursor.y - height).into());
Some(section)
}
/// Tries to add a new line and returns `true` if the area was large enough to fit the new
/// line.
#[must_use]
pub fn add_newline(&mut self) -> bool {
if self.cursor.y + self.line_height > self.area.size.height {
false
} else {
self.layer().add_line_break();
self.cursor.y += self.line_height;
true
}
}
/// Prints the given string with the given style.
///
/// The font cache for this text section must contain the PDF font for the given style.
pub fn print_str(&mut self, s: impl AsRef<str>, style: Style) -> Result<(), Error> {
let font = style.font(self.font_cache);
let positions = font
.kerning(self.font_cache, s.as_ref().chars())
.into_iter()
// Kerning is measured in 1/1000 em
.map(|pos| pos * -1000.0)
.map(|pos| pos as i64);
let codepoints = if font.is_builtin() {
// Built-in fonts always use the Windows-1252 encoding
encode_win1252(s.as_ref())?
} else {
font.glyph_ids(&self.font_cache, s.as_ref().chars())
};
let font = self
.font_cache
.get_pdf_font(font)
.expect("Could not find PDF font in font cache");
if let Some(color) = style.color() {
self.layer().set_fill_color(color.into());
} else if self.fill_color.is_some() {
self.layer().set_fill_color(Color::Rgb(0, 0, 0).into());
}
self.fill_color = style.color();
self.layer().set_font(font, style.font_size().into());
self.layer()
.write_positioned_codepoints(positions.zip(codepoints.iter().copied()));
Ok(())
}
fn layer(&self) -> &printpdf::PdfLayerReference {
self.area.layer()
}
}
impl<'a, 'f, 'l> Drop for TextSection<'a, 'f, 'l> {
fn drop(&mut self) {
if self.fill_color.is_some() {
self.layer().set_fill_color(Color::Rgb(0, 0, 0).into());
}
self.layer().end_text_section();
}
}
/// Encodes the given string using the Windows-1252 encoding for use with built-in PDF fonts,
/// returning an error if it contains unsupported characters.
fn encode_win1252(s: &str) -> Result<Vec<u16>, Error> {
let bytes: Vec<_> = lopdf::Document::encode_text(Some("WinAnsiEncoding"), s)
.into_iter()
.map(u16::from)
.collect();
// Windows-1252 is a single-byte encoding, so one byte is one character.
if bytes.len() != s.chars().count() {
Err(Error::new(
format!(
"Tried to print a string with characters that are not supported by the \
Windows-1252 encoding with a built-in font: {}",
s
),
ErrorKind::UnsupportedEncoding,
))
} else {
Ok(bytes)
}
}
+530
View File
@@ -0,0 +1,530 @@
// SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Types for styled strings.
//!
//! A [`StyledString`][] is a [`String`][] with a [`Style`][] annotation. Accordingly, a
//! [`StyledStr`][] is a [`&str`][] with a [`Style`][] annotation, and a [`StyledCow`][] is either
//! a [`Cow<'_, str>`][] with a [`Style`][] annotation.
//!
//! A [`Style`][] is a combination of a [`FontFamily`][], a font size, a line spacing factor, a
//! [`Color`][] and a combination of [`Effect`][]s (bold or italic).
//!
//! # Example
//!
//! ```
//! use genpdf::style;
//! let style = style::Style::new().bold();
//! let ss1 = style::StyledStr::new("bold", style);
//! let ss2 = style::StyledStr::new("red", style::Color::Rgb(255, 0, 0));
//! ```
//!
//! [`Color`]: enum.Color.html
//! [`Effect`]: enum.Effect.html
//! [`FontFamily`]: ../fonts/struct.FontFamily.html
//! [`Style`]: struct.Style.html
//! [`StyledCow`]: struct.StyledCow.html
//! [`StyledStr`]: struct.StyledStr.html
//! [`StyledString`]: struct.StyledString.html
//! [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
//! [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
//! [`Cow<'_, str>`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html
use std::borrow;
use std::iter;
use crate::fonts;
use crate::Mm;
/// A color, represented by RGB, CMYK or Greyscale values.
///
/// For all variants, the possible values range from 0 to 255.
///
/// # Examples
///
/// ```
/// let red = genpdf::style::Color::Rgb(255, 0, 0);
/// let cyan = genpdf::style::Color::Cmyk(255, 0, 0, 0);
/// let grey = genpdf::style::Color::Greyscale(127);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Color {
/// An RGB color with red, green and blue values between 0 and 255.
Rgb(u8, u8, u8),
/// An CMYK color with cyan, magenta, yellow and key values between 0 and 255.
Cmyk(u8, u8, u8, u8),
/// A greyscale color with a value between 0 and 255.
Greyscale(u8),
}
impl From<Color> for printpdf::Color {
fn from(color: Color) -> printpdf::Color {
match color {
Color::Rgb(r, g, b) => printpdf::Color::Rgb(printpdf::Rgb::new(
f64::from(r) / 255.0,
f64::from(g) / 255.0,
f64::from(b) / 255.0,
None,
)),
Color::Cmyk(c, m, y, k) => printpdf::Color::Cmyk(printpdf::Cmyk::new(
f64::from(c) / 255.0,
f64::from(m) / 255.0,
f64::from(y) / 255.0,
f64::from(k) / 255.0,
None,
)),
Color::Greyscale(val) => {
printpdf::Color::Greyscale(printpdf::Greyscale::new(f64::from(val) / 255.0, None))
}
}
}
}
/// A text effect (bold or italic).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Effect {
/// Bold text.
Bold,
/// Italic text.
Italic,
}
/// A style annotation for a string.
///
/// The annotation consists of:
/// - a font family, see [`FontFamily`][] (defaults to the [`FontCache`][] default)
/// - a font size in points (defaults to 12)
/// - a line spacing factor, with 1 meaning single line spacing (defaults to 1)
/// - an outline color, see [`Color`][] (defaults to black)
/// - a combination of text effects, see [`Effect`][] (defaults to none)
///
/// All properties are optional. If they are not set, they can be inferred from parent styles or
/// from the defaults.
///
/// [`Color`]: enum.Color.html
/// [`Effect`]: enum.Effect.html
/// [`FontFamily`]: ../fonts/struct.FontFamily.html
/// [`FontCache`]: ../fonts/struct.FontCache.html
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Style {
font_family: Option<fonts::FontFamily<fonts::Font>>,
font_size: Option<u8>,
line_spacing: Option<f64>,
color: Option<Color>,
is_bold: bool,
is_italic: bool,
}
impl Style {
/// Creates a new style without settings.
pub fn new() -> Style {
Style::default()
}
/// Merges the given style into this style.
pub fn merge(&mut self, style: impl Into<Style>) {
let style = style.into();
if let Some(font_family) = style.font_family {
self.font_family = Some(font_family);
};
if let Some(font_size) = style.font_size {
self.font_size = Some(font_size);
}
if let Some(color) = style.color {
self.color = Some(color);
}
if style.is_bold {
self.is_bold = true;
}
if style.is_italic {
self.is_italic = true;
}
}
/// Combines this style and the given style and returns the result.
pub fn and(mut self, style: impl Into<Style>) -> Style {
self.merge(style);
self
}
/// Creates a new style by combining the given styles.
pub fn combine(left: impl Into<Style>, right: impl Into<Style>) -> Style {
left.into().and(right)
}
/// Returns the outline color for this style, if set.
pub fn color(&self) -> Option<Color> {
self.color
}
/// Returns whether the bold text effect is set.
pub fn is_bold(&self) -> bool {
self.is_bold
}
/// Returns whether the italic text effect is set.
pub fn is_italic(&self) -> bool {
self.is_italic
}
/// Returns the font size for this style in points, or 12 if no font size is set.
pub fn font_size(&self) -> u8 {
self.font_size.unwrap_or(12)
}
/// Returns the line spacing factor for this style, or 1 if no line spacing factor is set.
pub fn line_spacing(&self) -> f64 {
self.line_spacing.unwrap_or(1.0)
}
/// Sets the bold effect for this style.
pub fn set_bold(&mut self) {
self.is_bold = true;
}
/// Sets the bold effect for this style and returns it.
pub fn bold(mut self) -> Style {
self.set_bold();
self
}
/// Sets the italic effect for this style.
pub fn set_italic(&mut self) {
self.is_italic = true;
}
/// Sets the italic effect for this style and returns it.
pub fn italic(mut self) -> Style {
self.set_italic();
self
}
/// Sets the font family for this style.
pub fn set_font_family(&mut self, font_family: fonts::FontFamily<fonts::Font>) {
self.font_family = Some(font_family);
}
/// Sets the font family for this style and returns it.
pub fn with_font_family(mut self, font_family: fonts::FontFamily<fonts::Font>) -> Style {
self.set_font_family(font_family);
self
}
/// Sets the line spacing factor for this style.
pub fn set_line_spacing(&mut self, line_spacing: f64) {
self.line_spacing = Some(line_spacing);
}
/// Sets the line spacing factor for this style and returns it.
pub fn with_line_spacing(mut self, line_spacing: f64) -> Style {
self.set_line_spacing(line_spacing);
self
}
/// Sets the font size in points for this style.
pub fn set_font_size(&mut self, font_size: u8) {
self.font_size = Some(font_size);
}
/// Sets the font size in points for this style and returns it.
pub fn with_font_size(mut self, font_size: u8) -> Style {
self.set_font_size(font_size);
self
}
/// Sets the outline color for this style.
pub fn set_color(&mut self, color: Color) {
self.color = Some(color);
}
/// Sets the outline color for this style and returns it.
pub fn with_color(mut self, color: Color) -> Self {
self.set_color(color);
self
}
/// Calculates the width of the given character with this style using the data in the given
/// font cache.
///
/// If the font family is set, it must have been created by the given [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn char_width(&self, font_cache: &fonts::FontCache, c: char) -> Mm {
self.font(font_cache)
.char_width(font_cache, c, self.font_size())
}
/// Calculates the width of the given string with this style using the data in the given font
/// cache.
///
/// If the font family is set, it must have been created by the given [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn str_width(&self, font_cache: &fonts::FontCache, s: &str) -> Mm {
let font = self.font(font_cache);
font.str_width(font_cache, s, self.font_size())
}
/// Returns the font family for this style or the default font family using the given font
/// cache.
///
/// If the font family is set, it must have been created by the given [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn font_family(&self, font_cache: &fonts::FontCache) -> fonts::FontFamily<fonts::Font> {
self.font_family
.unwrap_or_else(|| font_cache.default_font_family())
}
/// Returns the font for this style using the given font cache.
///
/// If the font family is set, it must have been created by the given [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn font(&self, font_cache: &fonts::FontCache) -> fonts::Font {
self.font_family(font_cache).get(*self)
}
/// Calculates the line height for strings with this style using the data in the given font
/// cache.
///
/// If the font family is set, it must have been created by the given [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn line_height(&self, font_cache: &fonts::FontCache) -> Mm {
self.font(font_cache).get_line_height(self.font_size()) * self.line_spacing()
}
}
impl From<Color> for Style {
fn from(color: Color) -> Style {
Style::new().with_color(color)
}
}
impl From<Effect> for Style {
fn from(effect: Effect) -> Style {
let style = Style::new();
match effect {
Effect::Bold => style.bold(),
Effect::Italic => style.italic(),
}
}
}
impl From<fonts::FontFamily<fonts::Font>> for Style {
fn from(font_family: fonts::FontFamily<fonts::Font>) -> Style {
Style::new().with_font_family(font_family)
}
}
impl<T: Into<Style>> iter::Extend<T> for Style {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for style in iter {
self.merge(style.into());
}
}
}
impl<T: Into<Style>> iter::FromIterator<T> for Style {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Style {
let mut style = Style::new();
style.extend(iter);
style
}
}
/// A [`String`][] with a [`Style`][] annotation.
///
/// # Example
///
/// ```
/// use genpdf::style;
/// let ss1 = style::StyledString::new("bold".to_owned(), style::Effect::Bold);
/// let ss2 = style::StyledString::new("red".to_owned(), style::Color::Rgb(255, 0, 0));
/// ```
///
/// [`Style`]: struct.Style.html
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
#[derive(Clone, Debug, Default)]
pub struct StyledString {
/// The annotated string.
pub s: String,
/// The style annotation.
pub style: Style,
}
impl StyledString {
/// Creates a new styled string from the given string and style.
pub fn new(s: impl Into<String>, style: impl Into<Style>) -> StyledString {
StyledString {
s: s.into(),
style: style.into(),
}
}
/// Calculates the width of the this string with this style using the data in the given font
/// cache.
///
/// If the font family is set for the style, it must have been created by the given
/// [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn width(&self, font_cache: &fonts::FontCache) -> Mm {
self.style.str_width(font_cache, &self.s)
}
}
impl From<String> for StyledString {
fn from(s: String) -> StyledString {
StyledString::new(s, Style::new())
}
}
impl<'a> From<&'a String> for StyledString {
fn from(s: &'a String) -> StyledString {
StyledString::from(s.to_owned())
}
}
impl<'a> From<&'a str> for StyledString {
fn from(s: &'a str) -> StyledString {
StyledString::from(s.to_owned())
}
}
/// A [`&str`][] with a [`Style`][] annotation.
///
/// # Example
///
/// ```
/// use genpdf::style;
/// let ss1 = style::StyledStr::new("bold", style::Effect::Bold);
/// let ss2 = style::StyledStr::new("red", style::Color::Rgb(255, 0, 0));
/// ```
///
/// [`Style`]: struct.Style.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[derive(Clone, Copy, Debug, Default)]
pub struct StyledStr<'s> {
/// The annotated string.
pub s: &'s str,
/// The style annotation.
pub style: Style,
}
impl<'s> StyledStr<'s> {
/// Creates a new styled string from the given string and style.
pub fn new(s: &'s str, style: impl Into<Style>) -> StyledStr<'s> {
StyledStr {
s,
style: style.into(),
}
}
/// Calculates the width of the this string with this style using the data in the given font
/// cache.
///
/// If the font family is set for the style, it must have been created by the given
/// [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn width(&self, font_cache: &fonts::FontCache) -> Mm {
self.style.str_width(font_cache, &self.s)
}
}
impl<'s> From<&'s str> for StyledStr<'s> {
fn from(s: &'s str) -> StyledStr<'s> {
StyledStr::new(s, Style::new())
}
}
impl<'s> From<&'s String> for StyledStr<'s> {
fn from(s: &'s String) -> StyledStr<'s> {
StyledStr::new(s, Style::new())
}
}
impl<'s> From<&'s StyledString> for StyledStr<'s> {
fn from(s: &'s StyledString) -> StyledStr<'s> {
StyledStr::new(&s.s, s.style)
}
}
/// A [`Cow<'s, str>`][] with a [`Style`][] annotation.
///
/// # Example
///
/// ```
/// use genpdf::style;
/// let ss1 = style::StyledCow::new("bold", style::Effect::Bold);
/// let ss2 = style::StyledCow::new("red".to_owned(), style::Color::Rgb(255, 0, 0));
/// ```
///
/// [`Style`]: struct.Style.html
/// [`Cow<'s, str>`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html
#[derive(Clone, Debug, Default)]
pub struct StyledCow<'s> {
/// The annotated string.
pub s: borrow::Cow<'s, str>,
/// The style annotation.
pub style: Style,
}
impl<'s> StyledCow<'s> {
/// Creates a new styled string from the given string and style.
pub fn new(s: impl Into<borrow::Cow<'s, str>>, style: impl Into<Style>) -> StyledCow<'s> {
StyledCow {
s: s.into(),
style: style.into(),
}
}
/// Calculates the width of the this string with this style using the data in the given font
/// cache.
///
/// If the font family is set for the style, it must have been created by the given
/// [`FontCache`][].
///
/// [`FontCache`]: ../fonts/struct.FontCache.html
pub fn width(&self, font_cache: &fonts::FontCache) -> Mm {
self.style.str_width(font_cache, self.s.as_ref())
}
}
impl<'s> From<&'s str> for StyledCow<'s> {
fn from(s: &'s str) -> StyledCow<'s> {
StyledCow::new(s, Style::new())
}
}
impl<'s> From<&'s String> for StyledCow<'s> {
fn from(s: &'s String) -> StyledCow<'s> {
StyledCow::new(s, Style::new())
}
}
impl<'s> From<String> for StyledCow<'s> {
fn from(s: String) -> StyledCow<'s> {
StyledCow::new(s, Style::new())
}
}
impl<'s> From<StyledStr<'s>> for StyledCow<'s> {
fn from(s: StyledStr<'s>) -> StyledCow<'s> {
StyledCow::new(s.s, s.style)
}
}
impl<'s> From<&'s StyledString> for StyledCow<'s> {
fn from(s: &'s StyledString) -> StyledCow<'s> {
StyledCow::new(&s.s, s.style)
}
}
impl<'s> From<StyledString> for StyledCow<'s> {
fn from(s: StyledString) -> StyledCow<'s> {
StyledCow::new(s.s, s.style)
}
}
+179
View File
@@ -0,0 +1,179 @@
// SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Utilities for text wrapping.
use std::mem;
use crate::style;
use crate::Context;
use crate::Mm;
/// Combines a sequence of styled words into lines with a maximum width.
///
/// If a word does not fit into a line, the wrapper tries to split it using the `split` function.
pub struct Wrapper<'c, 's, I: Iterator<Item = style::StyledStr<'s>>> {
iter: I,
context: &'c Context,
width: Mm,
x: Mm,
buf: Vec<style::StyledCow<'s>>,
}
impl<'c, 's, I: Iterator<Item = style::StyledStr<'s>>> Wrapper<'c, 's, I> {
/// Creates a new wrapper for the given word sequence and with the given maximum width.
pub fn new(iter: I, context: &'c Context, width: Mm) -> Wrapper<'c, 's, I> {
Wrapper {
iter,
context,
width,
x: Mm(0.0),
buf: Vec::new(),
}
}
}
impl<'c, 's, I: Iterator<Item = style::StyledStr<'s>>> Iterator for Wrapper<'c, 's, I> {
// This iterator yields pairs of lines and the length difference between the input words and
// the line.
type Item = (Vec<style::StyledCow<'s>>, usize);
fn next(&mut self) -> Option<(Vec<style::StyledCow<'s>>, usize)> {
// Append words to self.buf until the maximum line length is reached
while let Some(s) = self.iter.next() {
let mut width = s.width(&self.context.font_cache);
if self.x + width > self.width {
// The word does not fit into the current line (at least not completely)
let mut delta = 0;
// Try to split the word so that the first part fits into the current line
let s = if let Some((start, end)) = split(self.context, s, self.width - self.x) {
// Calculate the number of bytes that we added to the string when splitting it
// (for the hyphen, if required).
delta = start.s.len() + end.s.len() - s.s.len();
self.buf.push(start);
width = end.width(&self.context.font_cache);
end
} else {
s.into()
};
if width > self.width {
// The remainder of the word is longer than the current page – we will never be
// able to render it completely.
// TODO: return error?
break;
}
// Return the current line and add the word that did not fit to the next line
let v = std::mem::take(&mut self.buf);
self.buf.push(s);
self.x = width;
return Some((v, delta));
} else {
// The word fits in the current line, so just append it
self.buf.push(s.into());
self.x += width;
}
}
if self.buf.is_empty() {
None
} else {
Some((mem::take(&mut self.buf), 0))
}
}
}
#[cfg(not(feature = "hyphenation"))]
fn split<'s>(
_context: &Context,
_s: style::StyledStr<'s>,
_len: Mm,
) -> Option<(style::StyledCow<'s>, style::StyledCow<'s>)> {
None
}
/// Tries to split the given string into two parts so that the first part is shorter than the given
/// width.
#[cfg(feature = "hyphenation")]
fn split<'s>(
context: &Context,
s: style::StyledStr<'s>,
width: Mm,
) -> Option<(style::StyledCow<'s>, style::StyledCow<'s>)> {
use hyphenation::{Hyphenator, Iter};
let hyphenator = if let Some(hyphenator) = &context.hyphenator {
hyphenator
} else {
return None;
};
let mark = "-";
let mark_width = s.style.str_width(&context.font_cache, mark);
let hyphenated = hyphenator.hyphenate(s.s);
let segments: Vec<_> = hyphenated.iter().segments().collect();
// Find the hyphenation with the longest first part so that the first part (and the hyphen) are
// shorter than or equals to the required width.
let idx = segments
.iter()
.scan(Mm(0.0), |acc, t| {
*acc += s.style.str_width(&context.font_cache, t);
Some(*acc)
})
.position(|w| w + mark_width > width)
.unwrap_or_default();
if idx > 0 {
let idx = hyphenated.breaks[idx - 1];
let start = s.s[..idx].to_owned() + mark;
let end = &s.s[idx..];
Some((
style::StyledCow::new(start, s.style),
style::StyledCow::new(end, s.style),
))
} else {
None
}
}
/// Splits a sequence of styled strings into words.
pub struct Words<I: Iterator<Item = style::StyledString>> {
iter: I,
s: Option<style::StyledString>,
}
impl<I: Iterator<Item = style::StyledString>> Words<I> {
/// Creates a new words iterator.
pub fn new<IntoIter: IntoIterator<Item = style::StyledString, IntoIter = I>>(
iter: IntoIter,
) -> Words<I> {
Words {
iter: iter.into_iter(),
s: None,
}
}
}
impl<I: Iterator<Item = style::StyledString>> Iterator for Words<I> {
type Item = style::StyledString;
fn next(&mut self) -> Option<style::StyledString> {
if self.s.as_ref().map(|s| s.s.is_empty()).unwrap_or(true) {
self.s = self.iter.next();
}
if let Some(s) = &mut self.s {
// Split at the first space or use the complete string
let n = s.s.find(' ').map(|i| i + 1).unwrap_or_else(|| s.s.len());
let mut tmp = s.s.split_off(n);
mem::swap(&mut tmp, &mut s.s);
Some(style::StyledString::new(tmp, s.style))
} else {
None
}
}
}