Paint rules and frames as native PDF rectangles
This commit is contained in:
1 parent
4aa1714923
commit
be6f8859c2
36 files changed
+8967
-53
No files matched your search
Generated
-2
@@ -338,8 +338,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "genpdf"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1c422344482708cb32db843cf3f55f27918cd24fec7b505bde895a1e8702c34"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"image",
|
||||
|
||||
@@ -33,6 +33,9 @@ rmp-serde = "1.3"
|
||||
tiny_http = "0.12"
|
||||
ttf-parser = "0.25.1"
|
||||
|
||||
[patch.crates-io]
|
||||
genpdf = { path = "vendor/genpdf" }
|
||||
|
||||
[patch."https://github.com/jamespfennell/texcraft"]
|
||||
texlang = { path = "vendor/texlang" }
|
||||
texlang-stdlib = { path = "vendor/texlang-stdlib" }
|
||||
|
||||
@@ -302,7 +302,9 @@ every line is centered without justification (natural spaces), so
|
||||
|
||||
`\rule[raise]{width}{height}` is rendered as a filled rectangle in both the
|
||||
PDF and the SVG preview, including raised and dropped rules; a zero-thickness
|
||||
rule reserves space without painting ink. `\fbox{...}` is an inline framed box:
|
||||
rule reserves space without painting ink. PDF rectangles are native path operators
|
||||
(vendored genpdf `fill_rect`/`draw_rect`), so rules and frames no longer create
|
||||
image XObjects. `\fbox{...}` is an inline framed box:
|
||||
the content is measured as a single unbreakable unit, wrapped in 3pt padding and
|
||||
a 0.4pt frame, and painted in both the PDF and the SVG preview.
|
||||
|
||||
|
||||
+3
-3
@@ -8,7 +8,9 @@ family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`,
|
||||
`\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations;
|
||||
footnotes/`\thanks`; figure/table `[htbp]` placement approximations; page
|
||||
styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`);
|
||||
and geometry-aware `\textwidth`/`\textheight` named length registers.
|
||||
geometry-aware `\textwidth`/`\textheight` named length registers; table of
|
||||
contents and figure/table lists; and native PDF rectangles for rules and
|
||||
frames (vendored genpdf `fill_rect`/`draw_rect`, no image XObjects).
|
||||
|
||||
## 1. Unified pagination
|
||||
|
||||
@@ -34,7 +36,5 @@ and geometry-aware `\textwidth`/`\textheight` named length registers.
|
||||
|
||||
## 4. PDF painting and title blocks (remaining)
|
||||
|
||||
- Paint rules and frames as native PDF rectangles (`printpdf` operators)
|
||||
instead of 1x1 image XObjects.
|
||||
- Let a document-level `\renewcommand{\maketitle}` contribute a real title
|
||||
block once the engine's title model can run box material.
|
||||
+3
-3
@@ -63,14 +63,14 @@ See `docs/ROADMAP.md` for concrete implementation plans.
|
||||
- Contents: entries use infinite glue instead of dotted leaders and only
|
||||
numbered headings plus captions are listed; per-chapter contents in
|
||||
book/report are not distinguished.
|
||||
- Miscellaneous: rules are painted with 1x1 images in PDF; a document-level
|
||||
\renewcommand{\maketitle} is ignored in favor of the engine title block.
|
||||
- Miscellaneous: a document-level `\renewcommand{\maketitle}` is ignored in
|
||||
favor of the engine title block.
|
||||
|
||||
## Verification
|
||||
|
||||
- `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to
|
||||
one A4 page each; the arXiv template project compiles to 3 Letter pages.
|
||||
- `cargo fmt --check` passes; `cargo test --offline` (32 tests: 28 compiler
|
||||
- `cargo fmt --check` passes; `cargo test --offline` (33 tests: 29 compiler
|
||||
integration tests + 4 server tests) covers the three examples, the arXiv
|
||||
fixture, floats/newpage, page styles and `\thispagestyle`, SVG/PDF output,
|
||||
project API, static frontend assets, path traversal, the legacy
|
||||
|
||||
+1
-11
@@ -402,17 +402,7 @@ impl PositionedFramedBox {
|
||||
});
|
||||
}
|
||||
if self.frame {
|
||||
let style = Style::new();
|
||||
area.draw_line(vec![Position::default(), Position::new(width, 0.0)], style);
|
||||
area.draw_line(
|
||||
vec![Position::new(0.0, height), Position::new(width, height)],
|
||||
style,
|
||||
);
|
||||
area.draw_line(vec![Position::default(), Position::new(0.0, height)], style);
|
||||
area.draw_line(
|
||||
vec![Position::new(width, 0.0), Position::new(width, height)],
|
||||
style,
|
||||
);
|
||||
area.draw_rect(Position::default(), Size::new(width, height), Style::new());
|
||||
}
|
||||
|
||||
let mut line_y = self.inset_mm;
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::fmt::Write as _;
|
||||
|
||||
use common::Scaled;
|
||||
use genpdf::{
|
||||
Alignment, Context, Element, Mm, Position, RenderResult, Rotation, Scale, Size,
|
||||
Alignment, Context, Element, Mm, Position, RenderResult, Size,
|
||||
fonts::{self, FontFamily},
|
||||
style::Style,
|
||||
};
|
||||
@@ -553,41 +553,21 @@ impl Element for TextLine {
|
||||
let top = layout.ascent - frame.raise - frame.ascent - frame.padding;
|
||||
let right = left + frame.width;
|
||||
let bottom = top + frame.ascent + frame.depth + frame.padding + frame.padding;
|
||||
area.draw_line(
|
||||
vec![Position::new(left, top), Position::new(right, top)],
|
||||
Style::new(),
|
||||
);
|
||||
area.draw_line(
|
||||
vec![Position::new(left, bottom), Position::new(right, bottom)],
|
||||
Style::new(),
|
||||
);
|
||||
area.draw_line(
|
||||
vec![Position::new(left, top), Position::new(left, bottom)],
|
||||
Style::new(),
|
||||
);
|
||||
area.draw_line(
|
||||
vec![Position::new(right, top), Position::new(right, bottom)],
|
||||
area.draw_rect(
|
||||
Position::new(left, top),
|
||||
Size::new(right - left, bottom - top),
|
||||
Style::new(),
|
||||
);
|
||||
}
|
||||
if !layout.rules.is_empty() {
|
||||
let mut black = image::RgbImage::new(1, 1);
|
||||
black.put_pixel(0, 0, image::Rgb([0_u8, 0, 0]));
|
||||
let black = image::DynamicImage::ImageRgb8(black);
|
||||
for rule in &layout.rules {
|
||||
let scale_x = f64::from(rule.width) * 300.0 / 25.4;
|
||||
let scale_y = f64::from(rule.height) * 300.0 / 25.4;
|
||||
area.add_image(
|
||||
&black,
|
||||
Position::new(
|
||||
rule.x + horizontal_offset,
|
||||
layout.ascent - rule.y_offset - rule.raise,
|
||||
),
|
||||
Scale::new(scale_x, scale_y),
|
||||
Rotation::default(),
|
||||
Some(300.0),
|
||||
);
|
||||
}
|
||||
for rule in &layout.rules {
|
||||
area.fill_rect(
|
||||
Position::new(
|
||||
rule.x + horizontal_offset,
|
||||
layout.ascent - rule.y_offset - rule.raise,
|
||||
),
|
||||
Size::new(rule.width, rule.height),
|
||||
Style::new().with_color(genpdf::style::Color::Rgb(0, 0, 0)),
|
||||
);
|
||||
}
|
||||
|
||||
let mut placements = Vec::with_capacity(layout.spans.len());
|
||||
|
||||
@@ -851,3 +851,23 @@ fn list_of_figures_lists_captions_and_pages() {
|
||||
assert!(svg.contains(">of</text>"), "missing figures heading word");
|
||||
assert!(svg.contains(">First</text>"), "missing caption entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_are_native_pdf_rectangles() {
|
||||
let source = r"\documentclass{article}
|
||||
\begin{document}
|
||||
Before.
|
||||
\rule{40mm}{5mm}
|
||||
\fbox{Framed box}
|
||||
After.
|
||||
\end{document}";
|
||||
let pdf = CompilerSession::default()
|
||||
.compile(source, "rules.tex")
|
||||
.expect("rule PDF");
|
||||
assert!(pdf.starts_with(b"%PDF-"));
|
||||
let text = String::from_utf8_lossy(&pdf);
|
||||
assert!(
|
||||
!text.contains("/Subtype /Image"),
|
||||
"rules should not be painted as image XObjects"
|
||||
);
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"v":1}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "12fea24895b470ce9b7ff43487035cfaec234185"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
/target
|
||||
Cargo.lock
|
||||
Vendored
+82
@@ -0,0 +1,82 @@
|
||||
<!---
|
||||
SPDX-FileCopyrightText: 2020-2021 Robin Krahl <robin.krahl@ireas.org>
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
-->
|
||||
|
||||
# v0.2.0 (2021-06-17)
|
||||
|
||||
This release improves the font handling, adds support for embedding images and
|
||||
contains many small improvements and bugfixes.
|
||||
|
||||
Thanks to Alexander Dean-Kennedy for implementing the images support and to
|
||||
Scott Steele for contributing a bug fix.
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
- Improve the font handling:
|
||||
- Make `FontFamily` generic over the font data type.
|
||||
- Make the fields of the `FontFamily` struct public.
|
||||
- Load the PDF font in `Renderer::load_font` from bytes instead of a path.
|
||||
- Separate font loading and font caching:
|
||||
- Replace the `load_font` and `load_font_family` methods of the `FontCache`
|
||||
struct with `add_font` and `add_font_family`, and the `load_font_family`
|
||||
method of `Document` with `add_font_family`.
|
||||
- Add the `FontData::load` method and the `fonts::load_from_files`
|
||||
function.
|
||||
- Change the arguments of the `FontCache::new` and `Decorator::new`
|
||||
methods.
|
||||
- Make the `Document::new`, `Document::add_font_family`, `FontCache::new`,
|
||||
`FontCache::add_font`, `FontCache::add_font_family` and `Font::new` methods
|
||||
infallible.
|
||||
- Add support for built-in fonts.
|
||||
- Added the `Error::UnsupportedEncoding` variant.
|
||||
- Change the return type of the `Area::print_str` and
|
||||
`TextSection::print_str` methods to return a `Result`.
|
||||
- Move the `FontCache` instance used during the rendering process to the new
|
||||
`Context` struct.
|
||||
- Remove the `Document::set_margins` method (use a `PageDecorator` instead).
|
||||
- Replace the `PdfprintError` variant of `ErrorKind` with `PdfError` and
|
||||
`PdfIndexError`.
|
||||
- Change the return type of `render::Area::text_section` from `Result<_, ()>`
|
||||
to `Option<_>`.
|
||||
- Bump the MSRV to 1.45.0.
|
||||
- Move `Alignment` struct out of `elements` module.
|
||||
|
||||
## Non-Breaking Changes
|
||||
|
||||
- Add the `StyledCow<'s>` struct that contains a `Cow<'s, str>` with a `Style`
|
||||
annotation.
|
||||
- Derive `Copy` for `StyledStr`.
|
||||
- Add support for hyphenation (enabled by the `hyphenation` feature).
|
||||
- Add the `PageBreak` element.
|
||||
- Implement `From<Vec<StyledString>>` for `Paragraph`.
|
||||
- Add the `PageDecorator` trait, the `SimplePageDecorator` implementation and
|
||||
the `Document::set_page_decorator` method to allow customization of all
|
||||
document pages.
|
||||
- Add support for kerning and add the `Font::kerning` and `Font::glyph_ids`
|
||||
methods.
|
||||
- Add the `error::Context` trait for easier error generation.
|
||||
- Add support for `Image` as a possible insertable element.
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
- Always use the configured paper size when adding new pages to a `Document`.
|
||||
|
||||
# v0.1.1 (2020-10-16)
|
||||
|
||||
This patch release adds some trait implementations and utility functions and
|
||||
improves the crate documentation.
|
||||
|
||||
Thanks to Matteo Bertini for contributions.
|
||||
|
||||
- Implement `From<&String>` for `StyledString`.
|
||||
- Derive `Add`, `AddAssign`, `Sub` and `SubAssign` for `Position` and `Size`.
|
||||
- Implement `From<Position>` for `printpdf::Point`.
|
||||
- Add `split_horizontally` method to `Area`.
|
||||
- Add `width` method to `StyledString` and `StyledStr`.
|
||||
- Add `font_cache` method to `Document`.
|
||||
|
||||
# v0.1.0 (2020-10-15)
|
||||
|
||||
Initial release with support for formatted text, text wrapping and basic
|
||||
shapes.
|
||||
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies
|
||||
#
|
||||
# If you believe there's an error in this file please file an
|
||||
# issue against the rust-lang/cargo repository. If you're
|
||||
# editing this file be aware that the upstream Cargo.toml
|
||||
# will likely look very different (and much more reasonable)
|
||||
|
||||
[package]
|
||||
edition = "2018"
|
||||
name = "genpdf"
|
||||
version = "0.2.0"
|
||||
authors = ["Robin Krahl <[email protected]>"]
|
||||
exclude = [".builds/*"]
|
||||
description = "User-friendly PDF generator written in pure Rust"
|
||||
homepage = "https://sr.ht/~ireas/genpdf-rs"
|
||||
documentation = "https://docs.rs/genpdf"
|
||||
readme = "README.md"
|
||||
keywords = ["pdf", "text", "layout"]
|
||||
categories = ["text-processing"]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://git.sr.ht/~ireas/genpdf-rs"
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[[example]]
|
||||
name = "images"
|
||||
required-features = ["images"]
|
||||
[dependencies.derive_more]
|
||||
version = "0.99"
|
||||
features = ["add", "add_assign", "from", "into", "mul", "mul_assign", "sum"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.hyphenation]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[dependencies.image]
|
||||
version = "0.23.12"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.lopdf]
|
||||
version = "0.26"
|
||||
|
||||
[dependencies.printpdf]
|
||||
version = "0.3.4"
|
||||
default-features = false
|
||||
|
||||
[dependencies.rusttype]
|
||||
version = "0.8"
|
||||
[dev-dependencies.float-cmp]
|
||||
version = "0.8"
|
||||
features = ["std"]
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.hyphenation]
|
||||
version = "0.8"
|
||||
features = ["embed_en-us"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
images = ["image", "printpdf/embedded_images"]
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
# SPDX-FileCopyrightText: 2020-2021 Robin Krahl <[email protected]>
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
[package]
|
||||
name = "genpdf"
|
||||
version = "0.2.0"
|
||||
authors = ["Robin Krahl <[email protected]>"]
|
||||
edition = "2018"
|
||||
description = "User-friendly PDF generator written in pure Rust"
|
||||
homepage = "https://sr.ht/~ireas/genpdf-rs"
|
||||
repository = "https://git.sr.ht/~ireas/genpdf-rs"
|
||||
documentation = "https://docs.rs/genpdf"
|
||||
keywords = ["pdf", "text", "layout"]
|
||||
categories = ["text-processing"]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
exclude = [".builds/*"]
|
||||
readme = "README.md"
|
||||
|
||||
[[example]]
|
||||
name = "images"
|
||||
required-features = ["images"]
|
||||
|
||||
[dependencies]
|
||||
lopdf = "0.26"
|
||||
rusttype = "0.8"
|
||||
|
||||
[dependencies.image]
|
||||
version = "0.23.12"
|
||||
default-features = false
|
||||
optional = true
|
||||
|
||||
[dependencies.hyphenation]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[dependencies.printpdf]
|
||||
version = "0.3.4"
|
||||
default-features = false
|
||||
|
||||
[dependencies.derive_more]
|
||||
version = "0.99"
|
||||
default-features = false
|
||||
features = ["add", "add_assign", "from", "into", "mul", "mul_assign", "sum"]
|
||||
|
||||
[dev-dependencies.float-cmp]
|
||||
version = "0.8"
|
||||
default-features = false
|
||||
features = ["std"]
|
||||
|
||||
[dev-dependencies.hyphenation]
|
||||
version = "0.8"
|
||||
features = ["embed_en-us"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
images = ["image", "printpdf/embedded_images"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
Apache License
|
||||
|
||||
Version 2.0, January 2004
|
||||
|
||||
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
|
||||
AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution
|
||||
as defined by Sections 1 through 9 of this document.
|
||||
|
||||
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||
owner that is granting the License.
|
||||
|
||||
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||
that control, are controlled by, or are under common control with that entity.
|
||||
For the purposes of this definition, "control" means (i) the power, direct
|
||||
or indirect, to cause the direction or management of such entity, whether
|
||||
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
|
||||
of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
|
||||
granted by this License.
|
||||
|
||||
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including
|
||||
but not limited to software source code, documentation source, and configuration
|
||||
files.
|
||||
|
||||
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation
|
||||
or translation of a Source form, including but not limited to compiled object
|
||||
code, generated documentation, and conversions to other media types.
|
||||
|
||||
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form,
|
||||
made available under the License, as indicated by a copyright notice that
|
||||
is included in or attached to the work (an example is provided in the Appendix
|
||||
below).
|
||||
|
||||
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form,
|
||||
that is based on (or derived from) the Work and for which the editorial revisions,
|
||||
annotations, elaborations, or other modifications represent, as a whole, an
|
||||
original work of authorship. For the purposes of this License, Derivative
|
||||
Works shall not include works that remain separable from, or merely link (or
|
||||
bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version
|
||||
of the Work and any modifications or additions to that Work or Derivative
|
||||
Works thereof, that is intentionally submitted to Licensor for inclusion in
|
||||
the Work by the copyright owner or by an individual or Legal Entity authorized
|
||||
to submit on behalf of the copyright owner. For the purposes of this definition,
|
||||
"submitted" means any form of electronic, verbal, or written communication
|
||||
sent to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems, and
|
||||
issue tracking systems that are managed by, or on behalf of, the Licensor
|
||||
for the purpose of discussing and improving the Work, but excluding communication
|
||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||
owner as "Not a Contribution."
|
||||
|
||||
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||
of whom a Contribution has been received by Licensor and subsequently incorporated
|
||||
within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this
|
||||
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
|
||||
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
|
||||
Derivative Works of, publicly display, publicly perform, sublicense, and distribute
|
||||
the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License,
|
||||
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
|
||||
no-charge, royalty-free, irrevocable (except as stated in this section) patent
|
||||
license to make, have made, use, offer to sell, sell, import, and otherwise
|
||||
transfer the Work, where such license applies only to those patent claims
|
||||
licensable by such Contributor that are necessarily infringed by their Contribution(s)
|
||||
alone or by combination of their Contribution(s) with the Work to which such
|
||||
Contribution(s) was submitted. If You institute patent litigation against
|
||||
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||
that the Work or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses granted to You
|
||||
under this License for that Work shall terminate as of the date such litigation
|
||||
is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or
|
||||
Derivative Works thereof in any medium, with or without modifications, and
|
||||
in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy
|
||||
of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that
|
||||
You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute,
|
||||
all copyright, patent, trademark, and attribution notices from the Source
|
||||
form of the Work, excluding those notices that do not pertain to any part
|
||||
of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution,
|
||||
then any Derivative Works that You distribute must include a readable copy
|
||||
of the attribution notices contained within such NOTICE file, excluding those
|
||||
notices that do not pertain to any part of the Derivative Works, in at least
|
||||
one of the following places: within a NOTICE text file distributed as part
|
||||
of the Derivative Works; within the Source form or documentation, if provided
|
||||
along with the Derivative Works; or, within a display generated by the Derivative
|
||||
Works, if and wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and do not modify the
|
||||
License. You may add Your own attribution notices within Derivative Works
|
||||
that You distribute, alongside or as an addendum to the NOTICE text from the
|
||||
Work, provided that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide
|
||||
additional or different license terms and conditions for use, reproduction,
|
||||
or distribution of Your modifications, or for any such Derivative Works as
|
||||
a whole, provided Your use, reproduction, and distribution of the Work otherwise
|
||||
complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
||||
Contribution intentionally submitted for inclusion in the Work by You to the
|
||||
Licensor shall be under the terms and conditions of this License, without
|
||||
any additional terms or conditions. Notwithstanding the above, nothing herein
|
||||
shall supersede or modify the terms of any separate license agreement you
|
||||
may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names,
|
||||
trademarks, service marks, or product names of the Licensor, except as required
|
||||
for reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
|
||||
in writing, Licensor provides the Work (and each Contributor provides its
|
||||
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied, including, without limitation, any warranties
|
||||
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
|
||||
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
|
||||
of using or redistributing the Work and assume any risks associated with Your
|
||||
exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether
|
||||
in tort (including negligence), contract, or otherwise, unless required by
|
||||
applicable law (such as deliberate and grossly negligent acts) or agreed to
|
||||
in writing, shall any Contributor be liable to You for damages, including
|
||||
any direct, indirect, special, incidental, or consequential damages of any
|
||||
character arising as a result of this License or out of the use or inability
|
||||
to use the Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all other commercial
|
||||
damages or losses), even if such Contributor has been advised of the possibility
|
||||
of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work
|
||||
or Derivative Works thereof, You may choose to offer, and charge a fee for,
|
||||
acceptance of support, warranty, indemnity, or other liability obligations
|
||||
and/or rights consistent with this License. However, in accepting such obligations,
|
||||
You may act only on Your own behalf and on Your sole responsibility, not on
|
||||
behalf of any other Contributor, and only if You agree to indemnify, defend,
|
||||
and hold each Contributor harmless for any liability incurred by, or claims
|
||||
asserted against, such Contributor by reason of your accepting any such warranty
|
||||
or additional liability. END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate
|
||||
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
|
||||
information. (Don't include the brackets!) The text should be enclosed in
|
||||
the appropriate comment syntax for the file format. We also recommend that
|
||||
a file or class name and description of purpose be included on the same "printed
|
||||
page" as the copyright notice for easier identification within third-party
|
||||
archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
|
||||
See the License for the specific language governing permissions and
|
||||
|
||||
limitations under the License.
|
||||
Vendored
+119
@@ -0,0 +1,119 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
CC0 1.0 Universal CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES
|
||||
NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE
|
||||
AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION
|
||||
ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE
|
||||
OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS
|
||||
LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION
|
||||
OR WORKS PROVIDED HEREUNDER.
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer exclusive
|
||||
Copyright and Related Rights (defined below) upon the creator and subsequent
|
||||
owner(s) (each and all, an "owner") of an original work of authorship and/or
|
||||
a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later claims
|
||||
of infringement build upon, modify, incorporate in other works, reuse and
|
||||
redistribute as freely as possible in any form whatsoever and for any purposes,
|
||||
including without limitation commercial purposes. These owners may contribute
|
||||
to the Commons to promote the ideal of a free culture and the further production
|
||||
of creative, cultural and scientific works, or to gain reputation or greater
|
||||
distribution for their Work in part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with
|
||||
a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or
|
||||
her Copyright and Related Rights in the Work and the meaning and intended
|
||||
legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be protected
|
||||
by copyright and related or neighboring rights ("Copyright and Related Rights").
|
||||
Copyright and Related Rights include, but are not limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work, subject
|
||||
to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data
|
||||
in a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal protection
|
||||
of databases, and under any national implementation thereof, including any
|
||||
amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time extensions),
|
||||
(iii) in any current or future medium and for any number of copies, and (iv)
|
||||
for any purpose whatsoever, including without limitation commercial, advertising
|
||||
or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the
|
||||
benefit of each member of the public at large and to the detriment of Affirmer's
|
||||
heirs and successors, fully intending that such Waiver shall not be subject
|
||||
to revocation, rescission, cancellation, termination, or any other legal or
|
||||
equitable action to disrupt the quiet enjoyment of the Work by the public
|
||||
as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account Affirmer's
|
||||
express Statement of Purpose. In addition, to the extent the Waiver is so
|
||||
judged Affirmer hereby grants to each affected person a royalty-free, non
|
||||
transferable, non sublicensable, non exclusive, irrevocable and unconditional
|
||||
license to exercise Affirmer's Copyright and Related Rights in the Work (i)
|
||||
in all territories worldwide, (ii) for the maximum duration provided by applicable
|
||||
law or treaty (including future time extensions), (iii) in any current or
|
||||
future medium and for any number of copies, and (iv) for any purpose whatsoever,
|
||||
including without limitation commercial, advertising or promotional purposes
|
||||
(the "License"). The License shall be deemed effective as of the date CC0
|
||||
was applied by Affirmer to the Work. Should any part of the License for any
|
||||
reason be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the remainder of
|
||||
the License, and in such case Affirmer hereby affirms that he or she will
|
||||
not (i) exercise any of his or her remaining Copyright and Related Rights
|
||||
in the Work or (ii) assert any associated claims and causes of action with
|
||||
respect to the Work, in either case contrary to Affirmer's express Statement
|
||||
of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered,
|
||||
licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or other
|
||||
defects, accuracy, or the present or absence of errors, whether or not discoverable,
|
||||
all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims
|
||||
responsibility for obtaining any necessary consents, permissions or other
|
||||
rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a party
|
||||
to this document and has no duty or obligation with respect to this CC0 or
|
||||
use of the Work.
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
MIT License Copyright (c) <year> <copyright holders>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice (including the next
|
||||
paragraph) shall be included in all copies or substantial portions of the
|
||||
Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
|
||||
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
|
||||
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+133
@@ -0,0 +1,133 @@
|
||||
<!---
|
||||
Copyright (C) 2020 Robin Krahl <robin.krahl@ireas.org>
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
-->
|
||||
|
||||
# genpdf-rs
|
||||
|
||||
A user-friendly PDF generator written in pure Rust.
|
||||
|
||||
[Documentation](https://docs.rs/genpdf)
|
||||
|
||||
`genpdf` is a high-level PDF generator built on top of [`printpdf`][] and
|
||||
[`rusttype`][]. It takes care of the page layout and text alignment and
|
||||
renders a document tree into a PDF document. All of its dependencies are
|
||||
written in Rust, so you don’t need any pre-installed libraries or tools.
|
||||
|
||||
[`printpdf`]: https://lib.rs/crates/printpdf
|
||||
[`rusttype`]: https://lib.rs/crates/rusttype
|
||||
|
||||
<!-- Keep in sync with src/lib.rs -->
|
||||
```rust
|
||||
// Load a font from the file system
|
||||
let font_family = genpdf::fonts::from_files("./fonts", "LiberationSans", None)
|
||||
.expect("Failed to load font family");
|
||||
// Create a document and set the default font family
|
||||
let mut doc = genpdf::Document::new(font_family);
|
||||
// Change the default settings
|
||||
doc.set_title("Demo document");
|
||||
// Customize the pages
|
||||
let mut decorator = genpdf::SimplePageDecorator::new();
|
||||
decorator.set_margins(10);
|
||||
doc.set_page_decorator(decorator);
|
||||
// Add one or more elements
|
||||
doc.push(genpdf::elements::Paragraph::new("This is a demo document."));
|
||||
// Render the document and write it to a file
|
||||
doc.render_to_file("output.pdf").expect("Failed to write PDF file");
|
||||
```
|
||||
|
||||
For a complete example with all supported elements, see the
|
||||
[`examples/demo.rs`][] file that generates [this PDF document][].
|
||||
|
||||
[`examples/demo.rs`]: https://git.sr.ht/~ireas/genpdf-rs/tree/master/examples/demo.rs
|
||||
[this PDF document]: https://genpdf-rs.ireas.org/examples/demo.pdf
|
||||
|
||||
For more information, see the [API documentation](https://docs.rs/genpdf).
|
||||
|
||||
## Features
|
||||
|
||||
- PDF generation in pure Rust
|
||||
- Text rendering with support for setting the font family, style and size as
|
||||
well as the text color and text effects (bold or italic) and with kerning
|
||||
- Text wrapping at word boundaries and optional hyphenation
|
||||
- Layout of elements sequentially or in tables
|
||||
- Rudimentary support for shapes
|
||||
- Page headers and custom page decorations
|
||||
- Embedding images (scale, position, rotate).
|
||||
|
||||
## Cargo Features
|
||||
|
||||
This crate has the following Cargo features (deactivated per default):
|
||||
|
||||
- `images`: Adds support for embedding images using the [`image`][] crate.
|
||||
- `hyphenation`: Adds support for hyphenation using the [`hyphenation`][] crate.
|
||||
|
||||
[`hyphenation`]: https://lib.rs/crates/hyphenation
|
||||
[`image`]: https://lib.rs/crates/image
|
||||
|
||||
## Roadmap
|
||||
|
||||
These features are currently not supported but planned for future versions:
|
||||
- Improved support for drawing shapes
|
||||
- Advanced text formatting
|
||||
|
||||
See also the [`genpdf-rs` issue tracker](https://todo.sr.ht/~ireas/genpdf-rs).
|
||||
|
||||
## Alternatives
|
||||
|
||||
- [`printpdf`][] is the low-level PDF library used by `genpdf`. It provides
|
||||
more control over the generated document, but you have to take care of all
|
||||
details like calculating the width and height of the rendered text, arranging
|
||||
the elements and distributing them on multiple pages.
|
||||
- [`latex`][] generates LaTeX documents from Rust. It requires a LaTex
|
||||
installation to generate the PDF files. Also, escaping user input is a
|
||||
non-trivial problem and not supported by the crate.
|
||||
- [`tectonic`][] is a TeX engine based on XeTeX. It is partly written in C and
|
||||
has some non-Rust dependencies.
|
||||
- [`wkhtmltopdf`][] generates PDF documents from HTML using the `wkhtmltox`
|
||||
library. It requires a pre-installed library and does not support custom
|
||||
elements.
|
||||
|
||||
[`latex`]: https://lib.rs/crates/latex
|
||||
[`tectonic`]: https://lib.rs/crates/tectonic
|
||||
[`wkhtmltopdf`]: https://lib.rs/crates/wkhtmltopdf
|
||||
|
||||
## Minimum Supported Rust Version
|
||||
|
||||
This crate supports at least Rust 1.45.0 or later.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions to this project are welcome! Please submit patches to the
|
||||
mailing list [~ireas/public-inbox@lists.sr.ht][] ([archive][]) using the
|
||||
`[PATCH genpdf-rs]` subject prefix. For more information, see the
|
||||
[Contributing Guide][].
|
||||
|
||||
[~ireas/public-inbox@lists.sr.ht]: mailto:~ireas/public-inbox@lists.sr.ht
|
||||
[archive]: https://lists.sr.ht/~ireas/public-inbox
|
||||
[Contributing Guide]: https://man.sr.ht/~ireas/guides/contributing.md
|
||||
|
||||
If you are looking for a good starting point, have a look at the [issues with
|
||||
the label “good first issue”][issues] in `genpdf-rs`’s issue tracker.
|
||||
|
||||
[issues]: https://todo.sr.ht/~ireas/genpdf-rs?search=label:%22good%20first%20issue%22%20status%3Aopen
|
||||
|
||||
## Contact
|
||||
|
||||
For bug reports, feature requests and other messages, please send a mail to
|
||||
[~ireas/public-inbox@lists.sr.ht][] ([archive][]) using the `[genpdf-rs]`
|
||||
prefix in the subject.
|
||||
|
||||
## License
|
||||
|
||||
This project is dual-licensed under the [Apache-2.0][] and [MIT][] licenses.
|
||||
The documentation and examples contained in this repository are licensed under
|
||||
the [Creative Commons Zero][CC0] license. You can find a copy of the license
|
||||
texts in the `LICENSES` directory.
|
||||
|
||||
`genpdf-rs` complies with [version 3.0 of the REUSE specification][reuse].
|
||||
|
||||
[Apache-2.0]: https://opensource.org/licenses/Apache-2.0
|
||||
[MIT]: https://opensource.org/licenses/MIT
|
||||
[CC0]: https://creativecommons.org/publicdomain/zero/1.0/
|
||||
[reuse]: https://reuse.software/practices/3.0/
|
||||
Vendored
+2942
File diff suppressed because it is too large.
Load diff
+2
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
Vendored
+330
@@ -0,0 +1,330 @@
|
||||
// SPDX-FileCopyrightText: 2020 Robin Krahl <[email protected]>
|
||||
// SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
//! This example generates a demo PDF document and writes it to the path that was passed as the
|
||||
//! first command-line argument. You may have to adapt the `FONT_DIRS`, `DEFAULT_FONT_NAME` and
|
||||
//! `MONO_FONT_NAME` constants for your system so that these files exist:
|
||||
//! - `{FONT_DIR}/{name}-Regular.ttf`
|
||||
//! - `{FONT_DIR}/{name}-Bold.ttf`
|
||||
//! - `{FONT_DIR}/{name}-Italic.ttf`
|
||||
//! - `{FONT_DIR}/{name}-BoldItalic.ttf`
|
||||
//! for `name` in {`DEFAULT_FONT_NAME`, `MONO_FONT_NAME`}.
|
||||
//!
|
||||
//! The generated document using the latest `genpdf-rs` release is available
|
||||
//! [here](https://genpdf-rs.ireas.org/examples/demo.pdf).
|
||||
|
||||
use std::env;
|
||||
|
||||
use genpdf::Alignment;
|
||||
use genpdf::Element as _;
|
||||
use genpdf::{elements, fonts, style};
|
||||
|
||||
const FONT_DIRS: &[&str] = &[
|
||||
"/usr/share/fonts/liberation",
|
||||
"/usr/share/fonts/truetype/liberation",
|
||||
];
|
||||
const DEFAULT_FONT_NAME: &'static str = "LiberationSans";
|
||||
const MONO_FONT_NAME: &'static str = "LiberationMono";
|
||||
const LOREM_IPSUM: &'static str =
|
||||
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut \
|
||||
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco \
|
||||
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in \
|
||||
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat \
|
||||
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
|
||||
|
||||
fn main() {
|
||||
let args: Vec<_> = env::args().skip(1).collect();
|
||||
if args.len() != 1 {
|
||||
panic!("Missing argument: output file");
|
||||
}
|
||||
let output_file = &args[0];
|
||||
|
||||
let font_dir = FONT_DIRS
|
||||
.iter()
|
||||
.filter(|path| std::path::Path::new(path).exists())
|
||||
.next()
|
||||
.expect("Could not find font directory");
|
||||
let default_font =
|
||||
fonts::from_files(font_dir, DEFAULT_FONT_NAME, Some(fonts::Builtin::Helvetica))
|
||||
.expect("Failed to load the default font family");
|
||||
let monospace_font = fonts::from_files(font_dir, MONO_FONT_NAME, Some(fonts::Builtin::Courier))
|
||||
.expect("Failed to load the monospace font family");
|
||||
|
||||
let mut doc = genpdf::Document::new(default_font);
|
||||
doc.set_title("genpdf Demo Document");
|
||||
doc.set_minimal_conformance();
|
||||
doc.set_line_spacing(1.25);
|
||||
|
||||
let mut decorator = genpdf::SimplePageDecorator::new();
|
||||
decorator.set_margins(10);
|
||||
decorator.set_header(|page| {
|
||||
let mut layout = elements::LinearLayout::vertical();
|
||||
if page > 1 {
|
||||
layout.push(
|
||||
elements::Paragraph::new(format!("Page {}", page)).aligned(Alignment::Center),
|
||||
);
|
||||
layout.push(elements::Break::new(1));
|
||||
}
|
||||
layout.styled(style::Style::new().with_font_size(10))
|
||||
});
|
||||
doc.set_page_decorator(decorator);
|
||||
|
||||
#[cfg(feature = "hyphenation")]
|
||||
{
|
||||
use hyphenation::Load;
|
||||
|
||||
doc.set_hyphenator(
|
||||
hyphenation::Standard::from_embedded(hyphenation::Language::EnglishUS)
|
||||
.expect("Failed to load hyphenation data"),
|
||||
);
|
||||
}
|
||||
|
||||
let monospace = doc.add_font_family(monospace_font);
|
||||
let code = style::Style::from(monospace).bold();
|
||||
let red = style::Color::Rgb(255, 0, 0);
|
||||
let blue = style::Color::Rgb(0, 0, 255);
|
||||
|
||||
doc.push(
|
||||
elements::Paragraph::new("genpdf Demo Document")
|
||||
.aligned(Alignment::Center)
|
||||
.styled(style::Style::new().bold().with_font_size(20)),
|
||||
);
|
||||
doc.push(elements::Break::new(1.5));
|
||||
doc.push(elements::Paragraph::new(
|
||||
"This document demonstrates how the genpdf crate generates PDF documents. Currently, \
|
||||
genpdf supports these elements:",
|
||||
));
|
||||
|
||||
let mut list = elements::UnorderedList::new();
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("Text", code)
|
||||
.string(", a single line of formatted text without wrapping."),
|
||||
);
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("Paragraph", code)
|
||||
.string(
|
||||
", one or more lines of formatted text with wrapping and an alignment (left, \
|
||||
center, right).",
|
||||
),
|
||||
);
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("FramedElement", code)
|
||||
.string(", a frame drawn around other elements."),
|
||||
);
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("PaddedElement", code)
|
||||
.string(", an element with an additional padding."),
|
||||
);
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("StyledElement", code)
|
||||
.string(", an element with new default style."),
|
||||
);
|
||||
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("UnorderedList", code)
|
||||
.string(", an unordered list of bullet points."),
|
||||
);
|
||||
|
||||
list.push(
|
||||
elements::LinearLayout::vertical()
|
||||
.element(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("OrderedList", code)
|
||||
.string(", an ordered list of bullet points."),
|
||||
)
|
||||
.element(
|
||||
elements::OrderedList::new()
|
||||
.element(elements::Paragraph::new("Just like this."))
|
||||
.element(elements::Paragraph::new("And this.")),
|
||||
),
|
||||
);
|
||||
|
||||
list.push(
|
||||
elements::LinearLayout::vertical()
|
||||
.element(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("BulletPoint", code)
|
||||
.string(", an element with a bullet point, just like in this list."),
|
||||
)
|
||||
.element(elements::BulletPoint::new(elements::Paragraph::new(
|
||||
"Of course, lists can also be nested.",
|
||||
)))
|
||||
.element(
|
||||
elements::BulletPoint::new(elements::Paragraph::new(
|
||||
"And you can change the bullet symbol.",
|
||||
))
|
||||
.with_bullet("•"),
|
||||
),
|
||||
);
|
||||
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("LinearLayout", code)
|
||||
.string(
|
||||
", a container that vertically stacks its elements. The root element of a \
|
||||
document is always a LinearLayout.",
|
||||
),
|
||||
);
|
||||
list.push(
|
||||
elements::Paragraph::default()
|
||||
.styled_string("TableLayout", code)
|
||||
.string(", a container that arranges its elements in rows and columns."),
|
||||
);
|
||||
list.push(elements::Paragraph::new("And some more utility elements …"));
|
||||
doc.push(list);
|
||||
doc.push(elements::Break::new(1.5));
|
||||
|
||||
doc.push(elements::Paragraph::new(
|
||||
"You already saw lists and formatted centered text. Here are some other examples:",
|
||||
));
|
||||
doc.push(elements::Paragraph::new("This is right-aligned text.").aligned(Alignment::Right));
|
||||
doc.push(
|
||||
elements::Paragraph::new("And this paragraph has a frame drawn around it and is colored.")
|
||||
.padded(genpdf::Margins::vh(0, 1))
|
||||
.framed()
|
||||
.styled(red),
|
||||
);
|
||||
doc.push(
|
||||
elements::Paragraph::new("You can also use other fonts if you want to.").styled(monospace),
|
||||
);
|
||||
doc.push(
|
||||
elements::Paragraph::default()
|
||||
.string("You can also ")
|
||||
.styled_string("combine ", red)
|
||||
.styled_string("multiple ", style::Style::from(blue).italic())
|
||||
.styled_string("formats", code)
|
||||
.string(" in one paragraph.")
|
||||
.styled(style::Style::new().with_font_size(16)),
|
||||
);
|
||||
doc.push(elements::Break::new(1.5));
|
||||
|
||||
doc.push(elements::Paragraph::new(
|
||||
"Embedding images also works using the 'images' feature.",
|
||||
));
|
||||
#[cfg(feature = "images")]
|
||||
images::do_image_test(&mut doc);
|
||||
|
||||
doc.push(elements::Paragraph::new("Here is an example table:"));
|
||||
|
||||
let mut table = elements::TableLayout::new(vec![1, 2]);
|
||||
table.set_cell_decorator(elements::FrameCellDecorator::new(true, false, false));
|
||||
table
|
||||
.row()
|
||||
.element(
|
||||
elements::Paragraph::new("Header 1")
|
||||
.styled(style::Effect::Bold)
|
||||
.padded(1),
|
||||
)
|
||||
.element(elements::Paragraph::new("Value 2").padded(1))
|
||||
.push()
|
||||
.expect("Invalid table row");
|
||||
table
|
||||
.row()
|
||||
.element(
|
||||
elements::Paragraph::new("Header 2")
|
||||
.styled(style::Effect::Bold)
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
elements::Paragraph::new(
|
||||
"A long paragraph to demonstrate how wrapping works in tables. Nice, right?",
|
||||
)
|
||||
.padded(1),
|
||||
)
|
||||
.push()
|
||||
.expect("Invalid table row");
|
||||
let list_layout = elements::LinearLayout::vertical()
|
||||
.element(elements::Paragraph::new(
|
||||
"Of course, you can use all other elements inside a table.",
|
||||
))
|
||||
.element(
|
||||
elements::UnorderedList::new()
|
||||
.element(elements::Paragraph::new("Even lists!"))
|
||||
.element(
|
||||
elements::Paragraph::new("And frames!")
|
||||
.padded(genpdf::Margins::vh(0, 1))
|
||||
.framed(),
|
||||
),
|
||||
);
|
||||
table
|
||||
.row()
|
||||
.element(
|
||||
elements::Paragraph::new("Header 3")
|
||||
.styled(style::Effect::Bold)
|
||||
.padded(1),
|
||||
)
|
||||
.element(list_layout.padded(1))
|
||||
.push()
|
||||
.expect("Invalid table row");
|
||||
doc.push(table);
|
||||
doc.push(elements::Break::new(1.5));
|
||||
|
||||
doc.push(elements::Paragraph::new(
|
||||
"Now let’s print a long table to demonstrate how page wrapping works:",
|
||||
));
|
||||
|
||||
let mut table = elements::TableLayout::new(vec![1, 5]);
|
||||
table.set_cell_decorator(elements::FrameCellDecorator::new(true, true, false));
|
||||
table
|
||||
.row()
|
||||
.element(
|
||||
elements::Paragraph::new("Index")
|
||||
.styled(style::Effect::Bold)
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
elements::Paragraph::new("Text")
|
||||
.styled(style::Effect::Bold)
|
||||
.padded(1),
|
||||
)
|
||||
.push()
|
||||
.expect("Invalid table row");
|
||||
for i in 0..10 {
|
||||
table
|
||||
.row()
|
||||
.element(elements::Paragraph::new(format!("#{}", i)).padded(1))
|
||||
.element(elements::Paragraph::new(LOREM_IPSUM).padded(1))
|
||||
.push()
|
||||
.expect("Invalid table row");
|
||||
}
|
||||
|
||||
doc.push(table);
|
||||
|
||||
doc.render_to_file(output_file)
|
||||
.expect("Failed to write output file");
|
||||
}
|
||||
|
||||
// Only import the images if the feature is enabled. This helps verify our handling of feature toggles.
|
||||
#[cfg(feature = "images")]
|
||||
mod images {
|
||||
use super::*;
|
||||
|
||||
const IMAGE_PATH_JPG: &'static str = "examples/images/test_image.jpg";
|
||||
|
||||
pub fn do_image_test(doc: &mut genpdf::Document) {
|
||||
doc.push(elements::Paragraph::new(
|
||||
"Here is an example image with default position/scale:",
|
||||
));
|
||||
doc.push(elements::Image::from_path(IMAGE_PATH_JPG).expect("Unable to load image"));
|
||||
doc.push(elements::Paragraph::new(
|
||||
"and here is one that is centered, rotated, and scaled some.",
|
||||
));
|
||||
doc.push(
|
||||
elements::Image::from_path(IMAGE_PATH_JPG)
|
||||
.expect("Unable to load image")
|
||||
.with_alignment(Alignment::Center)
|
||||
.with_scale(genpdf::Scale::new(0.5, 2))
|
||||
.with_clockwise_rotation(45.0),
|
||||
);
|
||||
doc.push(elements::Paragraph::new(
|
||||
"For a full example of image functionality, please see images.pdf.",
|
||||
));
|
||||
doc.push(elements::Break::new(1.5));
|
||||
}
|
||||
}
|
||||
Vendored
+205
@@ -0,0 +1,205 @@
|
||||
// SPDX-FileCopyrightText: 2020 Alexander Dean-Kennedy <[email protected]>
|
||||
// SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
use std::env;
|
||||
|
||||
use genpdf::Alignment;
|
||||
use genpdf::Element as _;
|
||||
use genpdf::{elements, fonts, style};
|
||||
|
||||
const FONT_DIRS: &[&str] = &[
|
||||
"/usr/share/fonts/liberation",
|
||||
"/usr/share/fonts/truetype/liberation",
|
||||
];
|
||||
const DEFAULT_FONT_NAME: &'static str = "LiberationSans";
|
||||
|
||||
const IMAGE_PATH_JPG: &'static str = "examples/images/test_image.jpg";
|
||||
const IMAGE_PATH_BMP: &'static str = "examples/images/test_image.bmp";
|
||||
const IMAGE_PATH_PNG: &'static str = "examples/images/test_image.png";
|
||||
|
||||
fn main() {
|
||||
let args: Vec<_> = env::args().skip(1).collect();
|
||||
if args.len() != 1 {
|
||||
panic!("Missing argument: output file");
|
||||
}
|
||||
let output_file = &args[0];
|
||||
|
||||
let font_dir = FONT_DIRS
|
||||
.iter()
|
||||
.filter(|path| std::path::Path::new(path).exists())
|
||||
.next()
|
||||
.expect("Could not find font directory");
|
||||
let default_font =
|
||||
fonts::from_files(font_dir, DEFAULT_FONT_NAME, Some(fonts::Builtin::Helvetica))
|
||||
.expect("Failed to load the default font family");
|
||||
|
||||
let mut doc = genpdf::Document::new(default_font);
|
||||
doc.set_title("genpdf Demo Document");
|
||||
doc.set_minimal_conformance();
|
||||
doc.set_line_spacing(1.25);
|
||||
|
||||
let mut decorator = genpdf::SimplePageDecorator::new();
|
||||
decorator.set_margins(10);
|
||||
decorator.set_header(|page| {
|
||||
let mut layout = elements::LinearLayout::vertical();
|
||||
if page > 1 {
|
||||
layout.push(
|
||||
elements::Paragraph::new(format!("Page {}", page)).aligned(Alignment::Center),
|
||||
);
|
||||
layout.push(elements::Break::new(1));
|
||||
}
|
||||
layout.styled(style::Style::new().with_font_size(10))
|
||||
});
|
||||
doc.set_page_decorator(decorator);
|
||||
|
||||
doc.push(
|
||||
elements::Paragraph::new("genpdf Image Tests")
|
||||
.aligned(Alignment::Center)
|
||||
.styled(style::Style::new().bold().with_font_size(20)),
|
||||
);
|
||||
doc.push(elements::Break::new(1.5));
|
||||
doc.push(elements::Paragraph::new(
|
||||
"You may also: override the position, dpi, and/or default line-breaks, etc. See image here =>"
|
||||
));
|
||||
|
||||
doc.push(
|
||||
elements::Image::from_path(IMAGE_PATH_JPG)
|
||||
.expect("Unable to load alt image")
|
||||
.with_position(genpdf::Position::new(170, -10)) // far over to right and down
|
||||
.with_clockwise_rotation(90.0),
|
||||
);
|
||||
|
||||
// adding a break to avoid the image posted above with an "absolute image.
|
||||
doc.push(elements::Break::new(2));
|
||||
|
||||
// IMAGE FILE TYPE HANDLING:
|
||||
doc.push(elements::Paragraph::new(
|
||||
"Table with image format/scaling tests:",
|
||||
));
|
||||
let mut img_table = elements::TableLayout::new(vec![2, 2, 2, 2]);
|
||||
img_table.set_cell_decorator(elements::FrameCellDecorator::new(true, true, false));
|
||||
img_table
|
||||
.row()
|
||||
.element(elements::Text::new("Format").padded(1))
|
||||
.element(elements::Text::new("1:1").padded(1))
|
||||
.element(elements::Text::new("Half Size").padded(1))
|
||||
.element(elements::Text::new("Double Size").padded(1))
|
||||
.push()
|
||||
.expect("Invalid row");
|
||||
for (ftype, path) in vec![
|
||||
("BMP", IMAGE_PATH_BMP),
|
||||
("JPG", IMAGE_PATH_JPG),
|
||||
("PNG", IMAGE_PATH_PNG),
|
||||
] {
|
||||
let img = elements::Image::from_path(path).expect("invalid image");
|
||||
img_table
|
||||
.row()
|
||||
.element(elements::Paragraph::new(ftype).padded(1))
|
||||
.element(img.clone().framed().padded(1))
|
||||
.element(
|
||||
img.clone()
|
||||
.with_scale(genpdf::Scale::new(0.5, 0.5))
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_scale(genpdf::Scale::new(2, 2))
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.push()
|
||||
.expect("Invalid row");
|
||||
}
|
||||
doc.push(img_table);
|
||||
|
||||
doc.push(elements::Break::new(2));
|
||||
doc.push(elements::Paragraph::new(
|
||||
"Table with image rotation/offset calculation tests:",
|
||||
));
|
||||
let mut rot_table = elements::TableLayout::new(vec![2, 2, 2, 2, 2, 2, 2]);
|
||||
rot_table.set_cell_decorator(elements::FrameCellDecorator::new(true, true, false));
|
||||
rot_table
|
||||
.row()
|
||||
.element(elements::Text::new("Rot").padded(1))
|
||||
.element(elements::Text::new("30°").padded(1))
|
||||
.element(elements::Text::new("45°").padded(1))
|
||||
.element(elements::Text::new("90°").padded(1))
|
||||
.element(elements::Text::new("120°").padded(1))
|
||||
.element(elements::Text::new("150°").padded(1))
|
||||
.element(elements::Text::new("180°").padded(1))
|
||||
.push()
|
||||
.expect("Invalid row");
|
||||
let img = elements::Image::from_path(IMAGE_PATH_JPG).expect("invalid image");
|
||||
rot_table
|
||||
.row()
|
||||
.element(elements::Text::new("Positive").padded(1))
|
||||
.element(img.clone().with_clockwise_rotation(30.0).framed().padded(1))
|
||||
.element(img.clone().with_clockwise_rotation(45.0).framed().padded(1))
|
||||
.element(img.clone().with_clockwise_rotation(90.0).framed().padded(1))
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(120.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(150.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(180.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.push()
|
||||
.expect("Invalid row");
|
||||
rot_table
|
||||
.row()
|
||||
.element(elements::Text::new("Negative").padded(1))
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(-30.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(-45.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(-90.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(-120.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(-150.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.element(
|
||||
img.clone()
|
||||
.with_clockwise_rotation(-180.0)
|
||||
.framed()
|
||||
.padded(1),
|
||||
)
|
||||
.push()
|
||||
.expect("Invalid row");
|
||||
doc.push(rot_table);
|
||||
|
||||
doc.render_to_file(output_file)
|
||||
.expect("Failed to write output file");
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
@@ -0,0 +1,4 @@
|
||||
SPDX-FileCopyrightText: 2019 Michal Klajban
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
Source: https://commons.wikimedia.org/wiki/File:Otira_River_in_Arthur%27s_Pass_National_Park,_New_Zealand.jpg
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,4 @@
|
||||
SPDX-FileCopyrightText: 2019 Michal Klajban
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
Source: https://commons.wikimedia.org/wiki/File:Otira_River_in_Arthur%27s_Pass_National_Park,_New_Zealand.jpg
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,4 @@
|
||||
SPDX-FileCopyrightText: 2019 Michal Klajban
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
Source: https://commons.wikimedia.org/wiki/File:Otira_River_in_Arthur%27s_Pass_National_Park,_New_Zealand.jpg
|
||||
Vendored
+1251
File diff suppressed because it is too large.
Load diff
Vendored
+516
@@ -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));
|
||||
}
|
||||
}
|
||||
Vendored
+163
@@ -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)
|
||||
}
|
||||
}
|
||||
Vendored
+490
@@ -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)?,
|
||||
})
|
||||
}
|
||||
Vendored
+1015
File diff suppressed because it is too large.
Load diff
Vendored
+588
@@ -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)
|
||||
}
|
||||
}
|
||||
Vendored
+530
@@ -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)
|
||||
}
|
||||
}
|
||||
Vendored
+179
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user