Compress embedded font streams in the PDF writer

This commit is contained in:
gloamxun committed 2026-10-19 22:15:27 +08:00
1 parent 369472e7f7
commit 4735d75c1f
80 files changed
+9119 -5

No files matched your search

Generated
-2
View File
@@ -598,8 +598,6 @@ dependencies = [
[[package]]
name = "printpdf"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a2472a184bcb128d0e3db65b59ebd11d010259a5e14fd9d048cba8f2c9302d4"
dependencies = [
"image",
"js-sys",
+1
View File
@@ -35,6 +35,7 @@ tiny_http = "0.12"
ttf-parser = "0.25.1"
[patch.crates-io]
printpdf = { path = "vendor/printpdf" }
genpdf = { path = "vendor/genpdf" }
[patch."https://github.com/jamespfennell/texcraft"]
+1 -1
View File
@@ -81,4 +81,4 @@ the requested size and an x offset.
Done: the paragraph now places against the full body goal and the title-note reserve is applied after it; `arxiv_fixture_is_three_letter_pages` asserts that page 1 contains the closing `See` line and keeps a 3 mm gap above the footnote.
- Fonts: pyftsubset bundles with retained glyph ids and filtered kern table bring the arXiv PDF to about 1.1 MB; exact per-document glyph subsetting remains a follow-up.
- Fonts: pyftsubset bundles with retained glyph ids and filtered kern table bring the arXiv PDF to about 0.99 MB; exact per-document glyph subsetting remains a follow-up; font programs are Flate-compressed in the PDF.
+2 -2
View File
@@ -139,7 +139,7 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- Compiler integration tests: 53; server tests: 4; total 57.
- `cargo fmt --check` passes.
- arXiv fixture: 3 Letter pages, ~1.1 MB; four serif faces and one monospace face embedded (bold/italic monospace falls back to the regular face). The bundled SubsetTTF faces are pyftsubset outputs with retained glyph ids and a filtered legacy kern table; a second smaller Latin-1/Greek tier is selected when the document charset fits.
- arXiv fixture: 3 Letter pages, ~0.99 MB; four serif faces and one monospace face embedded (bold/italic monospace falls back to the regular face). The bundled SubsetTTF faces are pyftsubset outputs with retained glyph ids and a filtered legacy kern table; a second smaller Latin-1/Greek tier is selected when the document charset fits.
- Title/author/date/Introduction baselines within 0.3 pt of the XeLaTeX
reference; page 1 keeps the closing section-2 line above the footnote.
- Table 61.1 mm wide (reference 61.2 mm) with `\multicolumn` spans and
@@ -148,4 +148,4 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- PDF link annotations are added by reopening the finished PDF with lopdf,
since printpdf 0.3.4 has no annotation API.
- Fonts: bundled reserved-glyph subsets in `assets/fonts-subset/` are used when the document charset is covered; arXiv PDF is about 1.1 MB with 58 tests.
- Fonts: bundled reserved-glyph subsets in `assets/fonts-subset/` are used when the document charset is covered; arXiv PDF is about 0.99 MB with 58 tests.
+1
View File
@@ -0,0 +1 @@
{"v":1}
+5
View File
@@ -0,0 +1,5 @@
{
"git": {
"sha1": "28446a613ee11f1e6e3d63af580ed9a49a659e06"
}
}
+6
View File
@@ -0,0 +1,6 @@
target/*
./*.pdf
./test_
test_
.vscode/*
.cargo/*
+24
View File
@@ -0,0 +1,24 @@
language: rust
rust:
- stable
- beta
- nightly
os:
- linux
- osx
cache: cargo
matrix:
fast_finish: true
script:
- cargo check --verbose --examples
- cargo check --verbose --no-default-features
- cargo check --verbose --features="embedded_images"
- cargo test --verbose
notifications:
email: false
+113
View File
@@ -0,0 +1,113 @@
# Changelog
## `0.3.4`
- Added bookmarks and clipping path support
- *Breaking*: PDFConformance default changed to not require XMP Metadata and embedded ICC profile by default
## `0.3.1`
- Fix issue with Fonts on iOS and macOS
- Updated dependencies
## `0.3.0`
- Upgrade `rusttype` to `0.8.2` (breaks semver for non-`edition = "2019"` compilers, hence the new version)
- Upgrade `time` to `0.2.1`
- Added `PdfDocument::empty`
## `0.2.12`
- Upgrade `image` to `0.22`
## `0.2.11`
- Update `lopdf`, fixes #27
## `0.2.10`
- Upgraded image to `0.20`
- Added `ColorType::Palette` for indexed colors
- Creating an image from a Dynamic image can't fail, so no Result is returned
## `0.2.9`
- Upgraded `lopdf` to 0.17, getting rid of large `chrono` dependency
- Removed unnecessary `rand` dependency
- Made `image` dependency optional
- Added function to create images from an `image::DynamicImage`
- **WARNING**: Image crate has now certain lesser-used image types disabled by default:
- .ico (ICO format)
- .tga (Targa Image File)
- .hdr (High Dynamic Range Image)
- .dxt (S3 Texture Compression)
- .webp (WEBP format)
**If you don't re-enable these features, image decoding might fail at runtime!**
The reason they were removed was because of compile-time performance. For extra speed
when JPEG decoding, please also turn on `jpeg_rayon`
- No other API removals or large API changes
- Notable: `cargo build --no-default-features` has now "only" 33 dependencies and
`printpdf` has a debug build time of roughly 20 seconds
## `0.2.8`
- Firefox PDF viewer now works correctly due to a bugfix regarding the embedded TTF font type
- No API changes
## `0.2.7`
- Fixed a bug (https://github.com/fschutt/printpdf/issues/20#issuecomment-409988462)
regarding incorrect generation of character map files for embedding fonts
- No API changes
## `0.2.6`
- Updated `image` dependency to 0.19.0
- Updated `rand` dependency to 0.5.0
- Removed `error-chain`-generated errors in favor of simpler error enums (slight code-breaking change)
- Removed `FontError`, since it wasn't used anywhere
- Publicly re-exported `rusttype::Error` because that prevented error handling in applications that use `printpdf`
## `0.2.5`
- Fixed important word-spacing bug. In any version from 0.2.3 to this release there was a bug
where the spacing between words wasn't adjusted correctly, because the horizontal advance width
wasn't been taken into account. This has been fixed
- `Pt` and `Mm` can now be multiplied and divided by `f64`, mostly to ease the use of using them with
projections
- New `utils::calculate_points_for_rect` and `utils::calculate_points_for_circle` functions make
it easier to create circles and squares in a PDF. They are only convenience functions, mostly
because PDF has no built-in notation for circles or squares.
## `0.2.4`
- Nothing changed, just a dependency update, because `rusttype` was yanked, so `printpdf 0.2.3`
doesn't build anymore
## `0.2.3`
- printpdf now uses rusttype and does not require freetype anymore! There was an ugly
character-spacing hack that was fixed. You should now be able to build printpdf on windows
without further setup.
- Millimeters and points are now strongly typed - instead of `f64`, you now must denote the
scale with `Pt(f64)`, `Mm(f64)` or `Px(f64)`. The `mm_to_pt!` and `pt_to_mm!` macros have
been dropped since you can now do true conversions between these types. The reason for this
change was because this raw `f64`-based conversion bit me hard while using the library.
- The `Line` now has a different API and no `new()` function anymore. This is because
`Line::new(true, false, true)` is less expressive than `Line { has_stroke: true, ... }`.
## `0.2.2`
- SVG functionality was removed (commented out), because it didn't work in the first place
and only increased build times. So there's no point in keeping functionality that nobody
ever used, because it didn't work.
- Removed dependency on `num`
- `PdfDocument::save()` now only has a `T: Write` bound instead of `T: Write + Seek`.
## `0.2.1`
- The `document.save()` method now needs a `BufWriter`, to enforce buffered output (breaking change).
- The `PdfDocument` now implements `Clone`, so you can write one document to multiple outputs.
- You can disable the automatic embedding of an ICC profile by using a `CustomPdfConformance`.
See `examples/no_icc.rs` for usage information.
- `set_outline_thickness` now accepts floating-point units
+30
View File
@@ -0,0 +1,30 @@
# Contribution and License
The goal of `printpdf` is to be a complete PDF library so you could technically go ahead and build an alternative Illustrator
just using this library. The library is commercially maintained by my company, Maps4Print (we make printable PDF maps from
OpenStreetMap data). It was thought of a library for mapping and GIS. Instantiating content, minimal file size (useful when
you have many polygons / roads / shapes) are the goals. It is thought for graphics-heavy PDF files, it may not fit your purpose
completely.
By contributing to this library, you license your code under the MIT license.
# Testing
I am a bit lazy with testing, I admit this. Each object should have, in an ideal case:
* One or multiple test testing that the object correctly serializes into an object or operation
* A test outputting the specific object with minimal extra PDF content to a `test_[object name].pdf` so that the effect of the object can be seen.
* A test showing that the object does not affect other objects (only sometimes necessary)
# General guides
* Keep your functions short (should fit vertically into one 1080p screen)
* Document at least on one line per function (or copy / paste from the Adobe reference)
* Files should be kept together by semantic function. It's OK to have many structs in one file as long as they belong together
(ex. the `extgstate.rs` file)
* Functions that add content to the document should begin with `add_`, functions that reuse references begin with `use_`,
functions that modify the state of something in the PDF should begin with `set_`.
Have fun!
-- Felix
Generated Vendored
+822
View File
@@ -0,0 +1,822 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "adler"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee2a4ec343196209d6594e19543ae87a39f96d5534d7174822a3ad825dd6ed7e"
[[package]]
name = "adler32"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"
[[package]]
name = "approx"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3"
dependencies = [
"num-traits",
]
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "base-x"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4521f3e3d031370679b3b140beb36dfe4801b09ac77e30c61941f97df3ef28b"
[[package]]
name = "bitflags"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "bumpalo"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e8c087f005730276d1096a652e92a8bacee2e2472bcc9715a74d2bec38b5820"
[[package]]
name = "bytemuck"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41aa2ec95ca3b5c54cf73c91acf06d24f4495d5f1b1c12506ae3483d646177ac"
[[package]]
name = "byteorder"
version = "1.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de"
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "const_fn"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd51eab21ab4fd6a3bf889e2d0958c0a6e3a61ad04260325e919e652a2a62826"
[[package]]
name = "crc32fast"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a"
dependencies = [
"cfg-if 1.0.0",
]
[[package]]
name = "crossbeam-channel"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775"
dependencies = [
"cfg-if 1.0.0",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94af6efb46fef72616855b036a624cf27ba656ffc9be1b9a3c931cfc7749a9a9"
dependencies = [
"cfg-if 1.0.0",
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1aaa739f95311c2c7887a76863f500026092fb1dce0161dab577e559ef3569d"
dependencies = [
"cfg-if 1.0.0",
"const_fn",
"crossbeam-utils",
"lazy_static",
"memoffset",
"scopeguard",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02d96d1e189ef58269ebe5b97953da3274d83a93af647c2ddd6f9dab28cedb8d"
dependencies = [
"autocfg",
"cfg-if 1.0.0",
"lazy_static",
]
[[package]]
name = "deflate"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174"
dependencies = [
"adler32",
"byteorder",
]
[[package]]
name = "discard"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0"
[[package]]
name = "dtoa"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134951f4028bdadb9b84baf4232681efbf277da25144b9b0ad65df75946c422b"
[[package]]
name = "either"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
[[package]]
name = "encoding"
version = "0.2.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec"
dependencies = [
"encoding-index-japanese",
"encoding-index-korean",
"encoding-index-simpchinese",
"encoding-index-singlebyte",
"encoding-index-tradchinese",
]
[[package]]
name = "encoding-index-japanese"
version = "1.20141219.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04e8b2ff42e9a05335dbf8b5c6f7567e5591d0d916ccef4e0b1710d32a0d0c91"
dependencies = [
"encoding_index_tests",
]
[[package]]
name = "encoding-index-korean"
version = "1.20141219.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dc33fb8e6bcba213fe2f14275f0963fd16f0a02c878e3095ecfdf5bee529d81"
dependencies = [
"encoding_index_tests",
]
[[package]]
name = "encoding-index-simpchinese"
version = "1.20141219.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d87a7194909b9118fc707194baa434a4e3b0fb6a5a757c73c3adb07aa25031f7"
dependencies = [
"encoding_index_tests",
]
[[package]]
name = "encoding-index-singlebyte"
version = "1.20141219.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3351d5acffb224af9ca265f435b859c7c01537c0849754d3db3fdf2bfe2ae84a"
dependencies = [
"encoding_index_tests",
]
[[package]]
name = "encoding-index-tradchinese"
version = "1.20141219.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd0e20d5688ce3cab59eb3ef3a2083a5c77bf496cb798dc6fcdb75f323890c18"
dependencies = [
"encoding_index_tests",
]
[[package]]
name = "encoding_index_tests"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a246d82be1c9d791c5dfde9a2bd045fc3cbba3fa2b11ad558f27d01712f00569"
[[package]]
name = "flate2"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7411863d55df97a419aa64cb4d2f167103ea9d767e2c54a1868b7ac3f6b47129"
dependencies = [
"cfg-if 1.0.0",
"crc32fast",
"libc",
"miniz_oxide 0.4.3",
]
[[package]]
name = "gif"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02efba560f227847cb41463a7395c514d127d4f74fff12ef0137fff1b84b96c4"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "hermit-abi"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aca5565f760fb5b220e499d72710ed156fdb74e631659e99377d9ebfbd13ae8"
dependencies = [
"libc",
]
[[package]]
name = "image"
version = "0.23.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce04077ead78e39ae8610ad26216aed811996b043d47beed5090db674f9e9b5"
dependencies = [
"bytemuck",
"byteorder",
"color_quant",
"gif",
"jpeg-decoder",
"num-iter",
"num-rational",
"num-traits",
"png",
"scoped_threadpool",
"tiff",
]
[[package]]
name = "itoa"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
[[package]]
name = "jpeg-decoder"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc797adac5f083b8ff0ca6f6294a999393d76e197c36488e2ef732c4715f6fa3"
dependencies = [
"byteorder",
"rayon",
]
[[package]]
name = "js-sys"
version = "0.3.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf3d7383929f7c9c7c2d0fa596f325832df98c3704f2c60553080f7127a58175"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb"
[[package]]
name = "linked-hash-map"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dd5a6d5999d9907cda8ed67bbd137d3af8085216c2ac62de5be860bd41f304a"
[[package]]
name = "log"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b"
dependencies = [
"cfg-if 0.1.10",
]
[[package]]
name = "lopdf"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b49a0272112719d0037ab63d4bb67f73ba659e1e90bc38f235f163a457ac16f3"
dependencies = [
"dtoa",
"encoding",
"flate2",
"itoa",
"linked-hash-map",
"log",
"lzw",
"time",
]
[[package]]
name = "lzw"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d947cbb889ed21c2a84be6ffbaebf5b4e0f4340638cba0444907e38b56be084"
[[package]]
name = "memoffset"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "157b4208e3059a8f9e78d559edc658e13df41410cb3ae03979c83130067fdd87"
dependencies = [
"autocfg",
]
[[package]]
name = "miniz_oxide"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435"
dependencies = [
"adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f2d26ec3309788e423cfbf68ad1800f061638098d76a83681af979dc4eda19d"
dependencies = [
"adler",
"autocfg",
]
[[package]]
name = "num-integer"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2021c8337a54d21aca0d59a92577a029af9431cb59b909b03252b9c164fad59"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [
"autocfg",
]
[[package]]
name = "num_cpus"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "ordered-float"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3305af35278dd29f46fcdd139e0b1fbfae2153f0e5928b39b035542dd31e37b7"
dependencies = [
"num-traits",
]
[[package]]
name = "png"
version = "0.16.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6"
dependencies = [
"bitflags",
"crc32fast",
"deflate",
"miniz_oxide 0.3.7",
]
[[package]]
name = "printpdf"
version = "0.3.4"
dependencies = [
"image",
"js-sys",
"log",
"lopdf",
"rusttype",
"time",
]
[[package]]
name = "proc-macro-hack"
version = "0.5.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rayon"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b0d8e0819fadc20c74ea8373106ead0600e3a67ef1fe8da56e39b9ae7275674"
dependencies = [
"autocfg",
"crossbeam-deque",
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ab346ac5921dc62ffa9f89b7a773907511cdfa5490c572ae9be1be33e8afa4a"
dependencies = [
"crossbeam-channel",
"crossbeam-deque",
"crossbeam-utils",
"lazy_static",
"num_cpus",
]
[[package]]
name = "rustc_version"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [
"semver",
]
[[package]]
name = "rusttype"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f61411055101f7b60ecf1041d87fb74205fb20b0c7a723f07ef39174cf6b4c0"
dependencies = [
"approx",
"ordered-float",
"stb_truetype",
]
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "scoped_threadpool"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8"
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "semver"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
dependencies = [
"semver-parser",
]
[[package]]
name = "semver-parser"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "serde"
version = "1.0.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06c64263859d87aa2eb554587e2d23183398d617427327cf2b3d0ed8c69e4800"
[[package]]
name = "serde_derive"
version = "1.0.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c84d3526699cd55261af4b941e4e725444df67aa4f9e6a3564f18030d12672df"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1500e84d27fe482ed1dc791a56eddc2f230046a040fa908c08bda1d9fb615779"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "sha1"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d"
[[package]]
name = "standback"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf906c8b8fc3f6ecd1046e01da1d8ddec83e48c8b08b84dcc02b585a6bedf5a8"
dependencies = [
"version_check",
]
[[package]]
name = "stb_truetype"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f77b6b07e862c66a9f3e62a07588fee67cd90a9135a2b942409f195507b4fb51"
dependencies = [
"byteorder",
]
[[package]]
name = "stdweb"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5"
dependencies = [
"discard",
"rustc_version",
"stdweb-derive",
"stdweb-internal-macros",
"stdweb-internal-runtime",
"wasm-bindgen",
]
[[package]]
name = "stdweb-derive"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef"
dependencies = [
"proc-macro2",
"quote",
"serde",
"serde_derive",
"syn",
]
[[package]]
name = "stdweb-internal-macros"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11"
dependencies = [
"base-x",
"proc-macro2",
"quote",
"serde",
"serde_derive",
"serde_json",
"sha1",
"syn",
]
[[package]]
name = "stdweb-internal-runtime"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0"
[[package]]
name = "syn"
version = "1.0.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2af957a63d6bd42255c359c93d9bfdb97076bd3b820897ce55ffbfbf107f44"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "tiff"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a53f4706d65497df0c4349241deddf35f84cee19c87ed86ea8ca590f4464437"
dependencies = [
"jpeg-decoder",
"miniz_oxide 0.4.3",
"weezl",
]
[[package]]
name = "time"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcdaeea317915d59b2b4cd3b5efcd156c309108664277793f5351700c02ce98b"
dependencies = [
"const_fn",
"libc",
"standback",
"stdweb",
"time-macros",
"version_check",
"winapi",
]
[[package]]
name = "time-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1"
dependencies = [
"proc-macro-hack",
"time-macros-impl",
]
[[package]]
name = "time-macros-impl"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5c3be1edfad6027c69f5491cf4cb310d1a71ecd6af742788c6ff8bced86b8fa"
dependencies = [
"proc-macro-hack",
"proc-macro2",
"quote",
"standback",
"syn",
]
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "version_check"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[package]]
name = "wasm-bindgen"
version = "0.2.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cd364751395ca0f68cafb17666eee36b63077fb5ecd972bbcd74c90c4bf736e"
dependencies = [
"cfg-if 1.0.0",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1114f89ab1f4106e5b55e688b828c0ab0ea593a1ea7c094b141b14cbaaec2d62"
dependencies = [
"bumpalo",
"lazy_static",
"log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6ac8995ead1f084a8dea1e65f194d0973800c7f571f6edd70adf06ecf77084"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a48c72f299d80557c7c62e37e7225369ecc0c963964059509fbafe917c7549"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e7811dd7f9398f14cc76efd356f98f03aa30419dea46aa810d71e819fc97158"
[[package]]
name = "weezl"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2bb9fc8309084dd7cd651336673844c1d47f8ef6d2091ec160b27f5c4aa277"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+68
View File
@@ -0,0 +1,68 @@
# 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]
name = "printpdf"
version = "0.3.4"
authors = ["Felix Schütt <[email protected]>"]
exclude = ["./assets/*", "./doc/*", "./examples/*"]
description = "Rust library for writing PDF files"
homepage = "https://github.com/fschutt/printpdf"
readme = "README.md"
keywords = ["pdf", "gui", "graphics", "wkhtmltopdf"]
categories = ["gui"]
license = "MIT"
repository = "https://github.com/fschutt/printpdf"
[dependencies.image]
version = "0.23"
features = ["gif", "jpeg", "png", "pnm", "tiff", "bmp"]
optional = true
default-features = false
[dependencies.log]
version = "0.4.8"
optional = true
[dependencies.lopdf]
version = "0.26"
default-features = false
[dependencies.rusttype]
version = "0.8.2"
features = ["std"]
default-features = false
[dependencies.time]
version = "0.2.11"
features = ["std"]
default-features = false
[features]
clippy = []
dds = ["image/dds"]
default = ["embedded_images"]
dxt = ["image/dxt"]
embedded_images = ["image"]
hdr = ["image/hdr"]
ico = ["image/ico"]
jpeg_rayon = ["image/jpeg_rayon"]
less-optimization = []
logging = ["log"]
tga = ["image/tga"]
webp = ["image/webp"]
[target."cfg(all(target_arch=\"wasm32\",target_os=\"unknown\"))".dependencies.js-sys]
version = "0.3.40"
[badges.appveyor]
repository = "fschutt/printpdf"
[badges.travis-ci]
repository = "fschutt/printpdf"
+45
View File
@@ -0,0 +1,45 @@
[package]
name = "printpdf"
version = "0.3.4"
authors = ["Felix Schütt <[email protected]>"]
repository = "https://github.com/fschutt/printpdf"
homepage = "https://github.com/fschutt/printpdf"
license = "MIT"
readme = "README.md"
description = "Rust library for writing PDF files"
keywords = ["pdf", "gui", "graphics", "wkhtmltopdf"]
categories = ["gui"]
exclude = ["./assets/*", "./doc/*", "./examples/*"]
[dependencies]
lopdf = { version = "0.26", default-features = false }
rusttype = { version = "0.8.2", default-features = false, features = ["std"] }
time = { version = "0.2.11", default-features = false, features = ["std"] }
log = { version = "0.4.8", optional = true }
[dependencies.image]
version = "0.23"
default-features = false
features = ["gif", "jpeg", "png", "pnm", "tiff", "bmp"]
optional = true
[features]
default = ["embedded_images"]
clippy = []
logging = ["log"]
embedded_images = ["image"]
ico = ["image/ico"]
tga = ["image/tga"]
hdr = ["image/hdr"]
jpeg_rayon = ["image/jpeg_rayon"]
dxt = ["image/dxt"]
dds = ["image/dds"]
webp = ["image/webp"]
less-optimization = []
[target.'cfg(all(target_arch="wasm32",target_os="unknown"))'.dependencies]
js-sys = "0.3.40"
[badges]
travis-ci = { repository = "fschutt/printpdf" }
appveyor = { repository = "fschutt/printpdf" }
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Felix Schütt
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 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.
+329
View File
@@ -0,0 +1,329 @@
# printpdf
[![Travis CI](https://travis-ci.org/fschutt/printpdf.svg?branch=master)](https://travis-ci.org/fschutt/printpdf) [![Appveyor](https://ci.appveyor.com/api/projects/status/2ioc0wopm5a8ixgm?svg=true)](https://ci.appveyor.com/project/fschutt/printpdf)
`printpdf` is a library designed for creating printable PDF documents.
[Crates.io](https://crates.io/crates/printpdf) | [Documentation](https://docs.rs/printpdf)
```toml,ignore
[dependencies]
printpdf = "0.3.2"
```
## Features
Currently, printpdf can only create new documents and write them, it cannot load existing documents yet.
- Page generation
- Layers (Illustrator like layers)
- Graphics (lines, shapes, bezier curves)
- Images (currently BMP/JPG/PNG only or generate your own images)
- Embedded fonts (TTF and OTF) with Unicode support
- Advanced graphics - overprint control, blending modes, etc.
- Advanced typography - character scaling, character spacing, superscript, subscript, outlining, etc.
- PDF layers (you should be able to open the PDF in Illustrator and have the layers appear)
## Getting started
### Writing PDF
#### Simple page
```rust
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(247.0), Mm(210.0), "Layer 1");
let (page2, layer1) = doc.add_page(Mm(10.0), Mm(250.0),"Page 2, Layer 1");
doc.save(&mut BufWriter::new(File::create("test_working.pdf").unwrap())).unwrap();
```
#### Adding graphical shapes
```rust
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
use std::iter::FromIterator;
let (doc, page1, layer1) = PdfDocument::new("printpdf graphics test", Mm(297.0), Mm(210.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
// Quadratic shape. The "false" determines if the next (following)
// point is a bezier handle (for curves)
// If you want holes, simply reorder the winding of the points to be
// counterclockwise instead of clockwise.
let points1 = vec![(Point::new(Mm(100.0), Mm(100.0)), false),
(Point::new(Mm(100.0), Mm(200.0)), false),
(Point::new(Mm(300.0), Mm(200.0)), false),
(Point::new(Mm(300.0), Mm(100.0)), false)];
// Is the shape stroked? Is the shape closed? Is the shape filled?
let line1 = Line {
points: points1,
is_closed: true,
has_fill: true,
has_stroke: true,
is_clipping_path: false,
};
// Triangle shape
// Note: Line is invisible by default, the previous method of
// constructing a line is recommended!
let mut line2 = Line::from_iter(vec![
(Point::new(Mm(150.0), Mm(150.0)), false),
(Point::new(Mm(150.0), Mm(250.0)), false),
(Point::new(Mm(350.0), Mm(250.0)), false)]);
line2.set_stroke(true);
line2.set_closed(false);
line2.set_fill(false);
line2.set_as_clipping_path(false);
let fill_color = Color::Cmyk(Cmyk::new(0.0, 0.23, 0.0, 0.0, None));
let outline_color = Color::Rgb(Rgb::new(0.75, 1.0, 0.64, None));
let mut dash_pattern = LineDashPattern::default();
dash_pattern.dash_1 = Some(20);
current_layer.set_fill_color(fill_color);
current_layer.set_outline_color(outline_color);
current_layer.set_outline_thickness(10.0);
// Draw first line
current_layer.add_shape(line1);
let fill_color_2 = Color::Cmyk(Cmyk::new(0.0, 0.0, 0.0, 0.0, None));
let outline_color_2 = Color::Greyscale(Greyscale::new(0.45, None));
// More advanced graphical options
current_layer.set_overprint_stroke(true);
current_layer.set_blend_mode(BlendMode::Seperable(SeperableBlendMode::Multiply));
current_layer.set_line_dash_pattern(dash_pattern);
current_layer.set_line_cap_style(LineCapStyle::Round);
current_layer.set_fill_color(fill_color_2);
current_layer.set_outline_color(outline_color_2);
current_layer.set_outline_thickness(15.0);
// draw second line
current_layer.add_shape(line2);
```
#### Adding images
Note: Images only get compressed in release mode. You might get huge PDFs (6 or more MB) in
debug mode. In release mode, the compression makes these files much smaller (~ 100 - 200 KB).
To make this process faster, use `BufReader` instead of directly reading from the file.
Images are currently not a top priority.
Scaling of images is implicitly done to fit one pixel = one dot at 300 dpi.
```rust
extern crate printpdf;
// imports the `image` library with the exact version that we are using
use printpdf::*;
use std::convert::From;
use std::fs::File;
fn main() {
let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(247.0), Mm(210.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
// currently, the only reliable file formats are bmp/jpeg/png
// this is an issue of the image library, not a fault of printpdf
let mut image_file = File::open("assets/img/BMP_test.bmp").unwrap();
let image = Image::try_from(image::bmp::BmpDecoder::new(&mut image_file).unwrap()).unwrap();
// translate x, translate y, rotate, scale x, scale y
// by default, an image is optimized to 300 DPI (if scale is None)
// rotations and translations are always in relation to the lower left corner
image.add_to_layer(current_layer.clone(), None, None, None, None, None, None);
// you can also construct images manually from your data:
let mut image_file_2 = ImageXObject {
width: Px(200),
height: Px(200),
color_space: ColorSpace::Greyscale,
bits_per_component: ColorBits::Bit8,
interpolate: true,
/* put your bytes here. Make sure the total number of bytes =
width * height * (bytes per component * number of components)
(e.g. 2 (bytes) x 3 (colors) for RGB 16bit) */
image_data: Vec::new(),
image_filter: None, /* does not work yet */
clipping_bbox: None, /* doesn't work either, untested */
};
let image2 = Image::from(image_file_2);
}
```
#### Adding fonts
Note: Fonts are shared between pages. This means that they are added to the document first
and then a reference to this one object can be passed to multiple pages. This is different to
images, for example, which can only be used once on the page they are created on (since that's
the most common use-case).
```rust
use printpdf::*;
use std::fs::File;
let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(247.0), Mm(210.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
let text = "Lorem ipsum";
let text2 = "unicode: стуфхfцчшщъыьэюя";
let font = doc.add_external_font(File::open("assets/fonts/RobotoMedium.ttf").unwrap()).unwrap();
let font2 = doc.add_external_font(File::open("assets/fonts/RobotoMedium.ttf").unwrap()).unwrap();
// text, font size, x from left edge, y from bottom edge, font
current_layer.use_text(text, 48, Mm(200.0), Mm(200.0), &font);
// For more complex layout of text, you can use functions
// defined on the PdfLayerReference
// Make sure to wrap your commands
// in a `begin_text_section()` and `end_text_section()` wrapper
current_layer.begin_text_section();
// setup the general fonts.
// see the docs for these functions for details
current_layer.set_font(&font2, 33);
current_layer.set_text_cursor(Mm(10.0), Mm(10.0));
current_layer.set_line_height(33);
current_layer.set_word_spacing(3000);
current_layer.set_character_spacing(10);
current_layer.set_text_rendering_mode(TextRenderingMode::Stroke);
// write two lines (one line break)
current_layer.write_text(text.clone(), &font2);
current_layer.add_line_break();
current_layer.write_text(text2.clone(), &font2);
current_layer.add_line_break();
// write one line, but write text2 in superscript
current_layer.write_text(text.clone(), &font2);
current_layer.set_line_offset(10);
current_layer.write_text(text2.clone(), &font2);
current_layer.end_text_section();
```
## Optimiziation
### Minimizing the size of generated PDFs
- By default, the PDF adherese to a "PDF conformance level", usually the PDF-X 1.4 Standard.
This means that the PDF includes a full ICC profile file (which is around 500KB large). To turn it off,
see the [no_icc example](https://github.com/fschutt/printpdf/blob/a6fa46dad0f273cfd181eeebec7dc61e02559b4f/examples/no_icc.rs):
```rust
let (mut doc, _page1, _layer1) = PdfDocument::new("printpdf no_icc test", Mm(297.0), Mm(210.0), "Layer 1");
doc = doc.with_conformance(PdfConformance::Custom(CustomPdfConformance {
requires_icc_profile: false,
requires_xmp_metadata: false,
.. Default::default()
}));
```
- In debug mode, the images, streams and fonts are not compressed for easier debugging. Try building
in release mode to optimize the size further.
## Changelog
See the CHANGELOG.md file.
## Further reading
The `PdfDocument` is hidden behind a `PdfDocumentReference`, which locks
the things you can do behind a facade. Pretty much all functions operate
on a `PdfLayerReference`, so that would be where to look for existing
functions or where to implement new functions. The `PdfDocumentReference`
is a reference-counted document. It uses the pages and layers for inner
mutablility, because
I ran into borrowing issues with the document. __IMPORTANT:__ All functions
that mutate the state of the document, "borrow" the document mutably for
the duration of the function. It is important that you don't borrow the
document twice (your program will crash if you do so). I have prevented
this wherever possible, by making the document only public to the crate
so you cannot lock it from outside of this library.
Images have to be added to the pages resources before using them. Meaning,
you can only use an image on the page that you added it to. Otherwise,
you may end up with a corrupt PDF.
Fonts are embedded using `freetype`. There is a `rusttype` branch in this
repository, but `rusttype` does fails to get the height of an unscaled
font correctly, so that's why you currently have to use `freetype`
Please report issues if you have any, especially if you see `BorrowMut`
errors (they should not happen). Kerning is currently not done, because
neither `freetype` nor `rusttype` can reliably read kerning data.
However, "correct" kerning / placement requires a full font shaping
engine, etc. This would be a completely different project.
For learning how a PDF is actually made, please read the
[wiki](https://github.com/fschutt/printpdf/wiki) (currently not
completely finished). When I began making this library, these resources
were not available anywhere, so I hope to help other people
with these topics. Reading the wiki is essential if you want to
contribute to this library.
## Goals and Roadmap
The goal of printpdf is to be a general-use PDF library, such as
libharu or similar. PDFs generated by printpdf should always adhere
to a PDF standard, except if you turn it off. Currently, only the
standard `PDF/X-3:2002` is covered (i.e. valid PDF according to Adobe
Acrobat). Over time, there will be more standards supported. Checking a
PDF for errors is currently only a stub.
### Planned features / Not done yet
The following features aren't implemented yet, most
- Clipping
- Aligning / layouting text
- Open Prepress Interface
- Halftoning images, Gradients, Patterns
- SVG / instantiated content
- Forms, annotations
- Bookmarks / Table of contents
- Conformance / error checking for various PDF standards
- Embedded Javascript
- Reading PDF
- Completion of printpdf wiki
## Testing
Currently the testing is pretty much non-existent, because PDF is very hard to test.
This should change over time: Testing should be done in two stages. First, test
the individual PDF objects, if the conversion into a PDF object is done correctly.
The second stage is manual inspection of PDF objects via Adobe Preflight.
Put the tests of the first stage in /tests/mod.rs. The second stage tests are
better to be handled inside the plugins' mod.rs file. `printpdf` depends highly
on [lopdf](https://github.com/J-F-Liu/lopdf), so you can either construct your
test object against a real type or a debug string of your serialized type.
Either way is fine - you just have to check that the test object is conform to
what PDF expects.
## Useful links
Here are some resources I found while working on this library:
[`PDFXPlorer`, shows the DOM tree of a PDF, needs .NET 2.0](http://www.o2sol.com/pdfxplorer/download.htm)
[Official PDF 1.7 reference](http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf)
[[GERMAN] How to embed unicode fonts in PDF](http://www.p2501.ch/pdf-howto/typographie/vollzugriff/direkt)
[PDF X/1-a Validator](https://www.pdf-online.com/osa/validate.aspx)
[PDF X/3 technical notes](http://www.pdfxreport.com/lib/exe/fetch.php?media=en:technote_pdfx_checks.pdf)
+6
View File
@@ -0,0 +1,6 @@
# printpdf
[![Travis CI](https://travis-ci.org/fschutt/printpdf.svg?branch=master)](https://travis-ci.org/fschutt/printpdf) [![Appveyor](https://ci.appveyor.com/api/projects/status/2ioc0wopm5a8ixgm?svg=true)](https://ci.appveyor.com/project/fschutt/printpdf)
[![Dependencies](https://deps.rs/repo/github/fschutt/printpdf/status.svg)](https://deps.rs/repo/github/fschutt/printpdf)
{{readme}}
+43
View File
@@ -0,0 +1,43 @@
environment:
global:
# This will be used as part of the zipfile name
# TODO change the project name
PROJECT_NAME: printpdf
# TODO feel free to delete targets/channels you don't need
matrix:
# Stable channel
- TARGET: i686-pc-windows-gnu
CHANNEL: stable
- TARGET: i686-pc-windows-msvc
CHANNEL: stable
# This target is commented out because for some reason appveyor only ships
# GCC in 32-bit mode, so when compiling miniz.c (require for zipping), it'll
# fail although the build itself will work fine (because nobody uses a 32-bit
# compiler anymore in the real world). Just use a 64-bit compiler and
# everything will work fine.
#
# - TARGET: x86_64-pc-windows-gnu
# CHANNEL: stable
- TARGET: x86_64-pc-windows-msvc
CHANNEL: stable
# Install Rust and Cargo
# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml)
install:
- appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe
- rustup-init -yv --default-toolchain %channel% --default-host %target%
- set PATH=%PATH%;%USERPROFILE%\.cargo\bin;C:\tools\mingw64\bin;C:\MinGW\bin
- gcc -v
- rustc -vV
- cargo -vV
# 'cargo test' takes care of building for us, so disable Appveyor's build stage. This prevents
# the "directory does not contain a project or solution file" error.
# source: https://github.com/starkat99/appveyor-rust/blob/master/appveyor.yml#L113
build: false
# Equivalent to Travis' `script` phase
# TODO modify this phase as you see fit
test_script:
- cargo check --verbose --examples
- cargo test --verbose
+94
View File
@@ -0,0 +1,94 @@
Copyright (c) 2010, Matt McInerney ([email protected]),
Copyright (c) 2011, Pablo Impallari (www.impallari.com|[email protected]),
Copyright (c) 2011, Rodrigo Fuenzalida (www.rfuenzalida.com|[email protected]), with Reserved Font Name Raleway
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+20
View File
@@ -0,0 +1,20 @@
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
fn main() {
let (doc, page1, _) = PdfDocument::new("printpdf page test", Mm(210.0), Mm(297.0), "Layer 1");
doc.add_bookmark("This is a bookmark", page1);
let (page2, _) = doc.add_page(Mm(297.0), Mm(210.0), "Page 2, Layer 1");
let _ = doc.get_page(page2).add_layer("Layer 3");
doc.add_bookmark("This is another bookmark", page2);
// If this is successful, you should see a PDF with two blank A4 pages and 2 bookmarks
doc.save(&mut BufWriter::new(
File::create("test_bookmark.pdf").unwrap(),
))
.unwrap();
}
+23
View File
@@ -0,0 +1,23 @@
//! Example on how to use a built-in font in a PDF
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
fn main() {
let (mut doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(500.0), Mm(300.0), "Layer 1");
doc = doc.with_conformance(PdfConformance::Custom(CustomPdfConformance {
requires_icc_profile: false,
requires_xmp_metadata: false,
.. Default::default()
}));
let current_layer = doc.get_page(page1).get_layer(layer1);
let text = "Lorem ipsum";
let font = doc.add_builtin_font(BuiltinFont::TimesBoldItalic).unwrap();
current_layer.use_text(text, 48.0, Mm(10.0), Mm(200.0), &font);
doc.save(&mut BufWriter::new(File::create("test_builtin_fonts.pdf").unwrap())).unwrap();
}
+44
View File
@@ -0,0 +1,44 @@
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
fn main() {
use printpdf::utils::{calculate_points_for_circle, calculate_points_for_rect};
let (doc, page1, layer1) = PdfDocument::new("printpdf circle test", Mm(210.0), Mm(297.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
let radius = Pt(40.0);
let offset_x = Pt(10.0);
let offset_y = Pt(50.0);
let line = Line {
points: calculate_points_for_circle(radius, offset_x, offset_y),
is_closed: true,
has_fill: true,
has_stroke: true,
is_clipping_path: false
};
current_layer.add_shape(line);
let scale_x_rect = Pt(40.0);
let scale_y_rect = Pt(10.0);
let offset_x_rect = Pt(20.0);
let offset_y_rect = Pt(5.0);
let line = Line {
points: calculate_points_for_rect(scale_x_rect, scale_y_rect, offset_x_rect, offset_y_rect),
is_closed: true,
has_fill: true,
has_stroke: true,
is_clipping_path: false
};
current_layer.add_shape(line);
doc.save(&mut BufWriter::new(File::create("test_circle.pdf").unwrap())).unwrap();
}
+60
View File
@@ -0,0 +1,60 @@
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
fn main() {
let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(500.0), Mm(300.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
let text = "Lorem ipsum";
let text2 = "dolor sit amet";
let mut font_reader = std::io::Cursor::new(include_bytes!("../assets/fonts/RobotoMedium.ttf").as_ref());
let font = doc.add_external_font(&mut font_reader).unwrap();
// `use_text` is a wrapper around making a simple string
current_layer.use_text(text, 48.0, Mm(10.0), Mm(200.0), &font);
// text fill color = blue
let blue = Rgb::new(13.0 / 256.0, 71.0 / 256.0, 161.0 / 256.0, None);
let orange = Rgb::new(244.0 / 256.0, 67.0 / 256.0, 54.0 / 256.0, None);
current_layer.set_fill_color(Color::Rgb(blue));
current_layer.set_outline_color(Color::Rgb(orange));
// For more complex layout of text, you can use functions
// defined on the PdfLayerReference
// Make sure to wrap your commands
// in a `begin_text_section()` and `end_text_section()` wrapper
current_layer.begin_text_section();
// setup the general fonts.
// see the docs for these functions for details
current_layer.set_font(&font, 33.0);
current_layer.set_text_cursor(Mm(10.0), Mm(100.0));
current_layer.set_line_height(33.0);
current_layer.set_word_spacing(3000.0);
current_layer.set_character_spacing(10.0);
// write two lines (one line break)
current_layer.write_text(text, &font);
current_layer.add_line_break();
current_layer.write_text(text2, &font);
current_layer.add_line_break();
current_layer.set_text_rendering_mode(TextRenderingMode::FillStroke);
current_layer.set_character_spacing(0.0);
current_layer.set_text_matrix(TextMatrix::Rotate(10.0));
// write one line, but write text2 in superscript
current_layer.write_text(text, &font);
current_layer.set_line_offset(10.0);
current_layer.set_text_rendering_mode(TextRenderingMode::Stroke);
current_layer.set_font(&font, 18.0);
current_layer.write_text(text2, &font);
current_layer.end_text_section();
doc.save(&mut BufWriter::new(File::create("test_fonts.pdf").unwrap())).unwrap();
}
+74
View File
@@ -0,0 +1,74 @@
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
use std::iter::FromIterator;
fn main() {
let (doc, page1, layer1) = PdfDocument::new("printpdf graphics test", Mm(297.0), Mm(297.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
// Quadratic shape. The "false" determines if the next (following)
// point is a bezier handle (for curves)
// If you want holes, simply reorder the winding of the points to be
// counterclockwise instead of clockwise.
let points1 = vec![(Point::new(Mm(100.0), Mm(100.0)), false),
(Point::new(Mm(100.0), Mm(200.0)), false),
(Point::new(Mm(300.0), Mm(200.0)), false),
(Point::new(Mm(300.0), Mm(100.0)), false)];
// Is the shape stroked? Is the shape closed? Is the shape filled?
let line1 = Line {
points: points1,
is_closed: true,
has_fill: true,
has_stroke: true,
is_clipping_path: false,
};
// Triangle shape
// Note: Line is invisible by default, the previous method of
// constructing a line is recommended!
let mut line2 = Line::from_iter(vec![
(Point::new(Mm(150.0), Mm(150.0)), false),
(Point::new(Mm(150.0), Mm(250.0)), false),
(Point::new(Mm(350.0), Mm(250.0)), false)]);
line2.set_closed(false);
line2.set_stroke(true);
line2.set_fill(false);
line2.set_as_clipping_path(false);
let fill_color = Color::Cmyk(Cmyk::new(0.0, 0.23, 0.0, 0.0, None));
let outline_color = Color::Rgb(Rgb::new(0.75, 1.0, 0.64, None));
let mut dash_pattern = LineDashPattern::default();
dash_pattern.dash_1 = Some(20);
current_layer.set_fill_color(fill_color);
current_layer.set_outline_color(outline_color);
current_layer.set_outline_thickness(10.0);
// Draw first line
current_layer.add_shape(line1);
let fill_color_2 = Color::Cmyk(Cmyk::new(0.0, 0.0, 0.0, 0.0, None));
let outline_color_2 = Color::Greyscale(Greyscale::new(0.45, None));
// More advanced graphical options
current_layer.set_overprint_stroke(true);
current_layer.set_blend_mode(BlendMode::Seperable(SeperableBlendMode::Multiply));
current_layer.set_line_dash_pattern(dash_pattern);
current_layer.set_line_cap_style(LineCapStyle::Round);
current_layer.set_line_join_style(LineJoinStyle::Round);
current_layer.set_fill_color(fill_color_2);
current_layer.set_outline_color(outline_color_2);
current_layer.set_outline_thickness(15.0);
// draw second line
current_layer.add_shape(line2);
// If this is successful, you should see a PDF two shapes, one rectangle
// and a dotted line
doc.save(&mut BufWriter::new(File::create("test_graphics.pdf").unwrap())).unwrap();
}
+26
View File
@@ -0,0 +1,26 @@
extern crate printpdf;
use printpdf::*;
use std::io::Cursor;
use image::bmp::BmpDecoder;
use std::fs::File;
use std::io::BufWriter;
fn main() {
let (doc, page1, layer1) = PdfDocument::new("printpdf graphics test", Mm(210.0), Mm(297.0), "Layer 1");
let current_layer = doc.get_page(page1).get_layer(layer1);
// currently, the only reliable file formats are bmp/jpeg/png
// this is an issue of the image library, not a fault of printpdf
let image_bytes = include_bytes!("../assets/img/BMP_test.bmp");
let mut reader = Cursor::new(image_bytes.as_ref());
let decoder = BmpDecoder::new(&mut reader).unwrap();
let image2 = Image::try_from(decoder).unwrap();
// layer,
image2.add_to_layer(current_layer.clone(), None, None, None, None, None, None);
doc.save(&mut BufWriter::new(File::create("test_image.pdf").unwrap())).unwrap();
}
+24
View File
@@ -0,0 +1,24 @@
//! Example to demonstrate how to remove the default ICC profile
//! Look at the file size (compared to the other tests!)
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
fn main() {
// This code creates the most minimal PDF file with 1.2 KB
// Currently, fonts need to use an embedded font, so if you need to write something, the file size
// will still be bloated (because of the embedded font)
// Also, OCG content is still enabled, even if you disable it here.
let (mut doc, _page1, _layer1) = PdfDocument::new("printpdf no_icc test", Mm(297.0), Mm(210.0), "Layer 1");
doc = doc.with_conformance(PdfConformance::Custom(CustomPdfConformance {
requires_icc_profile: false,
requires_xmp_metadata: false,
.. Default::default()
}));
doc.save(&mut BufWriter::new(File::create("test_no_icc.pdf").unwrap())).unwrap();
}
+20
View File
@@ -0,0 +1,20 @@
extern crate printpdf;
use printpdf::*;
use std::fs::File;
use std::io::BufWriter;
fn main() {
// To prevent empty documents, you must specify at least one page with one layer
// You can later on add more pages with the add_page() function
// You also have to specify the title of the PDF and the document creator
let (doc, _, _) = PdfDocument::new("printpdf page test", Mm(210.0), Mm(297.0), "Layer 1");
// You can add more pages and layers to the PDF.
// Just make sure you don't lose the references, otherwise, you can't add things to the layer anymore
let (page2, _) = doc.add_page(Mm(297.0), Mm(210.0),"Page 2, Layer 1");
let _ = doc.get_page(page2).add_layer("Layer 3");
// If this is successful, you should see a PDF with two blank A4 pages
doc.save(&mut BufWriter::new(File::create("test_pages.pdf").unwrap())).unwrap();
}
+62
View File
@@ -0,0 +1,62 @@
/// wasm32-unknown-unknown polyfill
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub use self::js_sys_date::OffsetDateTime;
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub use time::OffsetDateTime;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod js_sys_date {
use js_sys::Date;
#[derive(Debug, Clone)]
pub struct OffsetDateTime(Date);
impl OffsetDateTime {
#[inline(always)]
pub fn now_utc() -> Self {
let date = Date::new_0();
OffsetDateTime(date)
}
#[inline(always)]
pub fn now() -> Self {
let date = Date::new_0();
OffsetDateTime(date)
}
#[inline(always)]
pub fn format(&self, format: impl ToString) -> String {
// TODO
"".into()
}
#[inline(always)]
pub fn year(&self) -> u32 {
self.0.get_full_year()
}
#[inline(always)]
pub fn month(&self) -> u32 {
self.0.get_month() + 1u32
}
#[inline(always)]
pub fn day(&self) -> u32 {
self.0.get_date()
}
#[inline(always)]
pub fn hour(&self) -> u32 {
self.0.get_hours()
}
#[inline(always)]
pub fn minute(&self) -> u32 {
self.0.get_minutes()
}
#[inline(always)]
pub fn second(&self) -> u32 {
self.0.get_seconds()
}
}
}
+89
View File
@@ -0,0 +1,89 @@
//! Errors for printpdf
use std::error::Error as IError;
use std::io::Error as IoError;
use rusttype::Error as RusttypeError;
use std::fmt;
/// error_chain and failure are certainly nice, but completely overengineered
/// for this use-case. For example, neither of them allow error localization.
/// Additionally, debugging macros can get hairy really quick and matching with
/// `*e.kind()` or doing From conversions for other errors is really hard to do.
///
/// So in this case, the best form of error handling is to use the simple Rust-native
/// way: Just enums, `From` + pattern matching. No macros, except for this one.
///
/// What this macro does is (simplified): `impl From<$a> for $b { $b::$variant(error) }`
macro_rules! impl_from {
($from:ident, $to:ident::$variant:ident) => (
impl From<$from> for $to {
fn from(err: $from) -> Self {
$to::$variant(err.into())
}
}
)
}
#[derive(Debug)]
pub enum Error {
/// External: std::io::Error
Io(IoError),
/// External: rusttype::Error
Rusttype(RusttypeError),
/// PDF error
Pdf(PdfError),
/// Indexing error (please report if this happens, shouldn't happen)
Index(IndexError),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PdfError {
FontFaceError,
}
impl fmt::Display for PdfError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Invalid or corrupt font face")
}
}
impl IError for PdfError {}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum IndexError {
PdfPageIndexError,
PdfLayerIndexError,
PdfMarkerIndexError,
}
impl fmt::Display for IndexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::IndexError::*;
write!(f, "{}", match *self {
PdfPageIndexError => "Page index out of bounds",
PdfLayerIndexError => "PDF layer index out of bounds",
PdfMarkerIndexError => "PDF layer index out of bounds",
})
}
}
impl IError for IndexError {}
impl_from!(IoError, Error::Io);
impl_from!(RusttypeError, Error::Rusttype);
impl_from!(PdfError, Error::Pdf);
impl_from!(IndexError, Error::Index);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match *self {
Io(ref e) => write!(f, "{}", e),
Rusttype(ref e) => write!(f, "{}", e),
Pdf(ref e) => write!(f, "{}", e),
Index(ref e) => write!(f, "{}", e),
}
}
}
impl IError for Error {}
+178
View File
@@ -0,0 +1,178 @@
#![allow(dead_code)]
//! PDF constants for tags for reducing typing mistakes
/*
/// Special graphics state
"q";
"Q";
"cm";
/// Text objects
"BT";
"ET";
/// Text state
"Tc";
"Tw";
"Tz";
"TL";
"Tf";
"Tr";
"Ts";
/// Text positioning
"Td";
"TD";
"Tm";
"Tm";
"T*";
/// Text showing
"Tj";
"TJ";
/// Type 3 fonts
"d0";
"d1";
/// Shading patterns
"sh";
/// Inline images
"BI";
"ID";
"EI";
/// XObjects
"Do";
/// Marked content
"MP";
"DP";
"BMC";
"BDC";
"EMC";
/// Compatability
"BX";
"EX";
*/
/*
pub(crate) const PDF_TAG_COLOR_SPACE_LINE: &'static str = "cs";
pub(crate) const PDF_TAG_COLOR_SPACE_FILL: &'static str = "CS";
pub(crate) const PDF_TAG_SET_COLOR_SPACE_LINE: &'static str = "SCN";
pub(crate) const PDF_TAG_SET_COLOR_SPACE_FILL: &'static str = "scn";
pub(crate) const PDF_TAG_BEGIN_TEXT: &'static str = "BT";
pub(crate) const PDF_TAG_SET_TEXT_FONT: &'static str = "Tf";
pub(crate) const PDF_TAG_SET_TEXT_POSTION: &'static str = "Td";
pub(crate) const PDF_TAG_WRITE_TEXT_NO_KERN: &'static str = "Tj";
pub(crate) const PDF_TAG_WRITE_TEXT_WITH_KERN: &'static str = "TJ";
pub(crate) const PDF_TAG_END_TEXT: &'static str = "ET";
pub(crate) const PDF_TAG_SET_LINE_WIDTH: &'static str = "ET";
pub(crate) const PDF_TAG_MOVE_TO: &'static str = "w";
pub(crate) const PDF_TAG_3BEZIER_CURVE_V1: &'static str = "v";
pub(crate) const PDF_TAG_3BEZIER_CURVE_V2: &'static str = "y";
pub(crate) const PDF_TAG_4BEZIER_CURVE: &'static str = "c";
*/
/// ## General graphics state
/// Set line width
pub(crate) const OP_PATH_STATE_SET_LINE_WIDTH: &str = "w";
/// Set line join
pub(crate) const OP_PATH_STATE_SET_LINE_JOIN: &str = "J";
/// Set line cap
pub(crate) const OP_PATH_STATE_SET_LINE_CAP: &str = "j";
/// Set miter limit
pub(crate) const OP_PATH_STATE_SET_MITER_LIMIT: &str = "M";
/// Set line dash pattern
pub(crate) const OP_PATH_STATE_SET_LINE_DASH: &str = "d";
/// Set rendering intent
pub(crate) const OP_PATH_STATE_SET_RENDERING_INTENT: &str = "ri";
/// Set flatness tolerance
pub(crate) const OP_PATH_STATE_SET_FLATNESS_TOLERANCE: &str = "i";
/// (PDF 1.2) Set graphics state from parameter dictionary
pub(crate) const OP_PATH_STATE_SET_GS_FROM_PARAM_DICT: &str = "gs";
/// ## Color
/// stroking color space (PDF 1.1)
pub(crate) const OP_COLOR_SET_STROKE_CS: &str = "CS";
/// non-stroking color space (PDF 1.1)
pub(crate) const OP_COLOR_SET_FILL_CS: &str = "cs";
/// set stroking color (PDF 1.1)
pub(crate) const OP_COLOR_SET_STROKE_COLOR: &str = "SC";
/// set stroking color (PDF 1.2) with support for ICC, etc.
pub(crate) const OP_COLOR_SET_STROKE_COLOR_ICC: &str = "SCN";
/// set fill color (PDF 1.1)
pub(crate) const OP_COLOR_SET_FILL_COLOR: &str = "sc";
/// set fill color (PDF 1.2) with support for Icc, etc.
pub(crate) const OP_COLOR_SET_FILL_COLOR_ICC: &str = "scn";
/// Set the stroking color space to DeviceGray
pub(crate) const OP_COLOR_SET_STROKE_CS_DEVICEGRAY: &str = "G";
/// Set the fill color space to DeviceGray
pub(crate) const OP_COLOR_SET_FILL_CS_DEVICEGRAY: &str = "g";
/// Set the stroking color space to DeviceRGB
pub(crate) const OP_COLOR_SET_STROKE_CS_DEVICERGB: &str = "RG";
/// Set the fill color space to DeviceRGB
pub(crate) const OP_COLOR_SET_FILL_CS_DEVICERGB: &str = "rg";
/// Set the stroking color space to DeviceCMYK
pub(crate) const OP_COLOR_SET_STROKE_CS_DEVICECMYK: &str = "K";
/// Set the fill color to DeviceCMYK
pub(crate) const OP_COLOR_SET_FILL_CS_DEVICECMYK: &str = "k";
/// Path construction
/// Move to point
pub(crate) const OP_PATH_CONST_MOVE_TO: &str = "m";
/// Straight line to the two following points
pub(crate) const OP_PATH_CONST_LINE_TO: &str = "l";
/// Cubic bezier over four following points
pub(crate) const OP_PATH_CONST_4BEZIER: &str = "c";
/// Cubic bezier with two points in v1
pub(crate) const OP_PATH_CONST_3BEZIER_V1: &str = "v";
/// Cubic bezier with two points in v2
pub(crate) const OP_PATH_CONST_3BEZIER_V2: &str = "y";
/// Add rectangle to the path (width / height): x y width height re
pub(crate) const OP_PATH_CONST_RECT: &str = "re";
/// Close current sub-path (for appending custom patterns along line)
pub(crate) const OP_PATH_CONST_CLOSE_SUBPATH: &str = "h";
/// Current path is a clip path, non-zero winding order (usually in like `h W S`)
pub(crate) const OP_PATH_CONST_CLIP_NZ: &str = "W";
/// Current path is a clip path, non-zero winding order
pub(crate) const OP_PATH_CONST_CLIP_EO: &str = "W*";
/// Path painting
/// Stroke path
pub(crate) const OP_PATH_PAINT_STROKE: &str = "S";
/// Close and stroke path
pub(crate) const OP_PATH_PAINT_STROKE_CLOSE: &str = "s";
/// Fill path using nonzero winding number rule
pub(crate) const OP_PATH_PAINT_FILL_NZ: &str = "f";
/// Fill path using nonzero winding number rule (obsolete)
pub(crate) const OP_PATH_PAINT_FILL_NZ_OLD: &str = "F";
/// Fill path using even-odd rule
pub(crate) const OP_PATH_PAINT_FILL_EO: &str = "f*";
/// Fill and stroke path using nonzero winding number rule
pub(crate) const OP_PATH_PAINT_FILL_STROKE_NZ: &str = "B";
/// Close, fill and stroke path using nonzero winding number rule
pub(crate) const OP_PATH_PAINT_FILL_STROKE_CLOSE_NZ: &str = "b";
/// Fill and stroke path using even-odd rule
pub(crate) const OP_PATH_PAINT_FILL_STROKE_EO: &str = "B*";
/// Close, fill and stroke path using even odd rule
pub(crate) const OP_PATH_PAINT_FILL_STROKE_CLOSE_EO: &str = "b*";
/// End path without filling or stroking
pub(crate) const OP_PATH_PAINT_END: &str = "n";
/// These color profiles are included in the binary
pub const ICC_PROFILE_ECI_V2: &[u8] = include_bytes!("templates/CoatedFOGRA39.icc");
+35
View File
@@ -0,0 +1,35 @@
//! These indices are for library internal use only.
//! Use the `add_*` functions to get an index instead.
/// Index of the page (0-based)
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct PdfPageIndex(pub(crate) usize);
/// Index of the layer on the nth page
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct PdfLayerIndex(pub(crate) usize);
/// Index of the arbitrary content data
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct PdfContentIndex(pub(crate) usize);
/// Index of a font
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct FontIndex(pub(crate) PdfContentIndex);
impl Into<PdfContentIndex> for FontIndex {
fn into(self) -> PdfContentIndex
{
self.0
}
}
/// Index of a svg file
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct SvgIndex(pub(crate) PdfContentIndex);
impl Into<PdfContentIndex> for SvgIndex {
fn into(self) -> PdfContentIndex
{
self.0
}
}
+408
View File
@@ -0,0 +1,408 @@
//! `printpdf` is a library designed for creating printable PDF documents.
//!
//! [Crates.io](https://crates.io/crates/printpdf) | [Documentation](https://docs.rs/printpdf)
//!
//! ```toml,ignore
//! [dependencies]
//! printpdf = "0.3.2"
//! ```
//!
//! # Features
//!
//! Currently, printpdf can only write documents, not read them.
//!
//! - Page generation
//! - Layers (Illustrator like layers)
//! - Graphics (lines, shapes, bezier curves)
//! - Images (currently BMP/PNG/JPG only or generate your own images)
//! - Embedded fonts (TTF and OTF) with Unicode support
//! - Advanced graphics - overprint control, blending modes, etc.
//! - Advanced typography - character scaling, character spacing, superscript, subscript, outlining, etc.
//! - PDF layers (you should be able to open the PDF in Illustrator and have the layers appear)
//!
//! # Getting started
//!
//! ## Writing PDF
//!
//! ### Simple page
//!
//! ```rust
//! use printpdf::*;
//! use std::fs::File;
//! use std::io::BufWriter;
//!
//! let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(247.0), Mm(210.0), "Layer 1");
//! let (page2, layer1) = doc.add_page(Mm(10.0), Mm(250.0),"Page 2, Layer 1");
//!
//! doc.save(&mut BufWriter::new(File::create("test_working.pdf").unwrap())).unwrap();
//! ```
//!
//! ### Adding graphical shapes
//!
//! ```rust
//! use printpdf::*;
//! use std::fs::File;
//! use std::io::BufWriter;
//! use std::iter::FromIterator;
//!
//! let (doc, page1, layer1) = PdfDocument::new("printpdf graphics test", Mm(297.0), Mm(210.0), "Layer 1");
//! let current_layer = doc.get_page(page1).get_layer(layer1);
//!
//! // Quadratic shape. The "false" determines if the next (following)
//! // point is a bezier handle (for curves)
//! // If you want holes, simply reorder the winding of the points to be
//! // counterclockwise instead of clockwise.
//! let points1 = vec![(Point::new(Mm(100.0), Mm(100.0)), false),
//! (Point::new(Mm(100.0), Mm(200.0)), false),
//! (Point::new(Mm(300.0), Mm(200.0)), false),
//! (Point::new(Mm(300.0), Mm(100.0)), false)];
//!
//! // Is the shape stroked? Is the shape closed? Is the shape filled?
//! let line1 = Line {
//! points: points1,
//! is_closed: true,
//! has_fill: true,
//! has_stroke: true,
//! is_clipping_path: false,
//! };
//!
//! // Triangle shape
//! // Note: Line is invisible by default, the previous method of
//! // constructing a line is recommended!
//! let mut line2 = Line::from_iter(vec![
//! (Point::new(Mm(150.0), Mm(150.0)), false),
//! (Point::new(Mm(150.0), Mm(250.0)), false),
//! (Point::new(Mm(350.0), Mm(250.0)), false)]);
//!
//! line2.set_stroke(true);
//! line2.set_closed(false);
//! line2.set_fill(false);
//! line2.set_as_clipping_path(false);
//!
//! let fill_color = Color::Cmyk(Cmyk::new(0.0, 0.23, 0.0, 0.0, None));
//! let outline_color = Color::Rgb(Rgb::new(0.75, 1.0, 0.64, None));
//! let mut dash_pattern = LineDashPattern::default();
//! dash_pattern.dash_1 = Some(20);
//!
//! current_layer.set_fill_color(fill_color);
//! current_layer.set_outline_color(outline_color);
//! current_layer.set_outline_thickness(10.0);
//!
//! // Draw first line
//! current_layer.add_shape(line1);
//!
//! let fill_color_2 = Color::Cmyk(Cmyk::new(0.0, 0.0, 0.0, 0.0, None));
//! let outline_color_2 = Color::Greyscale(Greyscale::new(0.45, None));
//!
//! // More advanced graphical options
//! current_layer.set_overprint_stroke(true);
//! current_layer.set_blend_mode(BlendMode::Seperable(SeperableBlendMode::Multiply));
//! current_layer.set_line_dash_pattern(dash_pattern);
//! current_layer.set_line_cap_style(LineCapStyle::Round);
//!
//! current_layer.set_fill_color(fill_color_2);
//! current_layer.set_outline_color(outline_color_2);
//! current_layer.set_outline_thickness(15.0);
//!
//! // draw second line
//! current_layer.add_shape(line2);
//! ```
//!
//! ### Adding images
//!
//! Note: Images only get compressed in release mode. You might get huge PDFs (6 or more MB) in
//! debug mode. In release mode, the compression makes these files much smaller (~ 100 - 200 KB).
//!
//! To make this process faster, use `BufReader` instead of directly reading from the file.
//! Images are currently not a top priority.
//!
//! Scaling of images is implicitly done to fit one pixel = one dot at 300 dpi.
//!
//! ```rust
//! extern crate printpdf;
//!
//! // imports the `image` library with the exact version that we are using
//! use printpdf::*;
//!
//! use std::convert::From;
//! use std::fs::File;
//!
//! fn main() {
//! let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(247.0), Mm(210.0), "Layer 1");
//! let current_layer = doc.get_page(page1).get_layer(layer1);
//!
//! // currently, the only reliable file formats are bmp/jpeg/png
//! // this is an issue of the image library, not a fault of printpdf
//! let mut image_file = File::open("assets/img/BMP_test.bmp").unwrap();
//! let image = Image::try_from(image::bmp::BmpDecoder::new(&mut image_file).unwrap()).unwrap();
//!
//! // translate x, translate y, rotate, scale x, scale y
//! // by default, an image is optimized to 300 DPI (if scale is None)
//! // rotations and translations are always in relation to the lower left corner
//! image.add_to_layer(current_layer.clone(), None, None, None, None, None, None);
//!
//! // you can also construct images manually from your data:
//! let mut image_file_2 = ImageXObject {
//! width: Px(200),
//! height: Px(200),
//! color_space: ColorSpace::Greyscale,
//! bits_per_component: ColorBits::Bit8,
//! interpolate: true,
//! /* put your bytes here. Make sure the total number of bytes =
//! width * height * (bytes per component * number of components)
//! (e.g. 2 (bytes) x 3 (colors) for RGB 16bit) */
//! image_data: Vec::new(),
//! image_filter: None, /* does not work yet */
//! clipping_bbox: None, /* doesn't work either, untested */
//! };
//!
//! let image2 = Image::from(image_file_2);
//! }
//! ```
//!
//! ### Adding fonts
//!
//! Note: Fonts are shared between pages. This means that they are added to the document first
//! and then a reference to this one object can be passed to multiple pages. This is different to
//! images, for example, which can only be used once on the page they are created on (since that's
//! the most common use-case).
//!
//! ```rust
//! use printpdf::*;
//! use std::fs::File;
//!
//! let (doc, page1, layer1) = PdfDocument::new("PDF_Document_title", Mm(247.0), Mm(210.0), "Layer 1");
//! let current_layer = doc.get_page(page1).get_layer(layer1);
//!
//! let text = "Lorem ipsum";
//! let text2 = "unicode: стуфхfцчшщъыьэюя";
//!
//! let font = doc.add_external_font(File::open("assets/fonts/RobotoMedium.ttf").unwrap()).unwrap();
//! let font2 = doc.add_external_font(File::open("assets/fonts/RobotoMedium.ttf").unwrap()).unwrap();
//!
//! // text, font size, x from left edge, y from bottom edge, font
//! current_layer.use_text(text, 48.0, Mm(200.0), Mm(200.0), &font);
//!
//! // For more complex layout of text, you can use functions
//! // defined on the PdfLayerReference
//! // Make sure to wrap your commands
//! // in a `begin_text_section()` and `end_text_section()` wrapper
//! current_layer.begin_text_section();
//!
//! // setup the general fonts.
//! // see the docs for these functions for details
//! current_layer.set_font(&font2, 33.0);
//! current_layer.set_text_cursor(Mm(10.0), Mm(10.0));
//! current_layer.set_line_height(33.0);
//! current_layer.set_word_spacing(3000.0);
//! current_layer.set_character_spacing(10.0);
//! current_layer.set_text_rendering_mode(TextRenderingMode::Stroke);
//!
//! // write two lines (one line break)
//! current_layer.write_text(text.clone(), &font2);
//! current_layer.add_line_break();
//! current_layer.write_text(text2.clone(), &font2);
//! current_layer.add_line_break();
//!
//! // write one line, but write text2 in superscript
//! current_layer.write_text(text.clone(), &font2);
//! current_layer.set_line_offset(10.0);
//! current_layer.write_text(text2.clone(), &font2);
//!
//! current_layer.end_text_section();
//! ```
//!
//! ## Changelog
//!
//! See the CHANGELOG.md file.
//!
//! # Further reading
//!
//! The `PdfDocument` is hidden behind a `PdfDocumentReference`, which locks
//! the things you can do behind a facade. Pretty much all functions operate
//! on a `PdfLayerReference`, so that would be where to look for existing
//! functions or where to implement new functions. The `PdfDocumentReference`
//! is a reference-counted document. It uses the pages and layers for inner
//! mutablility, because
//! I ran into borrowing issues with the document. __IMPORTANT:__ All functions
//! that mutate the state of the document, "borrow" the document mutably for
//! the duration of the function. It is important that you don't borrow the
//! document twice (your program will crash if you do so). I have prevented
//! this wherever possible, by making the document only public to the crate
//! so you cannot lock it from outside of this library.
//!
//! Images have to be added to the pages resources before using them. Meaning,
//! you can only use an image on the page that you added it to. Otherwise,
//! you may end up with a corrupt PDF.
//!
//! Fonts are embedded using `freetype`. There is a `rusttype` branch in this
//! repository, but `rusttype` does fails to get the height of an unscaled
//! font correctly, so that's why you currently have to use `freetype`
//!
//! Please report issues if you have any, especially if you see `BorrowMut`
//! errors (they should not happen). Kerning is currently not done, because
//! neither `freetype` nor `rusttype` can reliably read kerning data.
//! However, "correct" kerning / placement requires a full font shaping
//! engine, etc. This would be a completely different project.
//!
//! For learning how a PDF is actually made, please read the
//! [wiki](https://github.com/fschutt/printpdf/wiki) (currently not
//! completely finished). When I began making this library, these resources
//! were not available anywhere, so I hope to help other people
//! with these topics. Reading the wiki is essential if you want to
//! contribute to this library.
//!
//! # Goals and Roadmap
//!
//! The goal of printpdf is to be a general-use PDF library, such as
//! libharu or similar. PDFs generated by printpdf should always adhere
//! to a PDF standard, except if you turn it off. Currently, only the
//! standard `PDF/X-3:2002` is covered (i.e. valid PDF according to Adobe
//! Acrobat). Over time, there will be more standards supported. Checking a
//! PDF for errors is currently only a stub.
//!
//! ## Planned features / Not done yet
//!
//! The following features aren't implemented yet, most
//! - Clipping
//! - Aligning / layouting text
//! - Open Prepress Interface
//! - Halftoning images, Gradients, Patterns
//! - SVG / instantiated content
//! - Forms, annotations
//! - Bookmarks / Table of contents
//! - Conformance / error checking for various PDF standards
//! - Embedded Javascript
//! - Reading PDF
//! - Completion of printpdf wiki
//!
//! # Testing
//!
//! Currently the testing is pretty much non-existent, because PDF is very hard to test.
//! This should change over time: Testing should be done in two stages. First, test
//! the individual PDF objects, if the conversion into a PDF object is done correctly.
//! The second stage is manual inspection of PDF objects via Adobe Preflight.
//!
//! Put the tests of the first stage in /tests/mod.rs. The second stage tests are
//! better to be handled inside the plugins' mod.rs file. `printpdf` depends highly
//! on [lopdf](https://github.com/J-F-Liu/lopdf), so you can either construct your
//! test object against a real type or a debug string of your serialized type.
//! Either way is fine - you just have to check that the test object is conform to
//! what PDF expects.
//!
//! # Useful links
//!
//! Here are some resources I found while working on this library:
//!
//! [`PDFXPlorer`, shows the DOM tree of a PDF, needs .NET 2.0](http://www.o2sol.com/pdfxplorer/download.htm)
//!
//! [Official PDF 1.7 reference](http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf)
//!
//! [[GERMAN] How to embed unicode fonts in PDF](http://www.p2501.ch/pdf-howto/typographie/vollzugriff/direkt)
//!
//! [PDF X/1-a Validator](https://www.pdf-online.com/osa/validate.aspx)
//!
//! [PDF X/3 technical notes](http://www.pdfxreport.com/lib/exe/fetch.php?media=en:technote_pdfx_checks.pdf)
// Enable clippy if our Cargo.toml file asked us to do so.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![warn(missing_copy_implementations,
trivial_numeric_casts,
trivial_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications)]
#![cfg_attr(feature="clippy", warn(cast_possible_truncation))]
#![cfg_attr(feature="clippy", warn(cast_possible_truncation))]
#![cfg_attr(feature="clippy", warn(cast_precision_loss))]
#![cfg_attr(feature="clippy", warn(cast_sign_loss))]
#![cfg_attr(feature="clippy", warn(missing_docs_in_private_items))]
#![cfg_attr(feature="clippy", warn(mut_mut))]
// Disallow `println!`. Use `debug!` for debug output
// (which is provided by the `log` crate).
#![cfg_attr(feature="clippy", warn(print_stdout))]
#![cfg_attr(all(not(test), feature="clippy"), warn(result_unwrap_used))]
#![cfg_attr(feature="clippy", warn(unseparated_literal_suffix))]
#![cfg_attr(feature="clippy", warn(wrong_pub_self_convention))]
#[cfg(feature = "logging")]
#[macro_use] pub extern crate log;
extern crate lopdf;
extern crate rusttype;
extern crate time;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
extern crate js_sys;
pub mod date;
#[cfg(feature = "embedded_images")]
pub extern crate image;
pub mod types;
pub mod scale;
pub mod errors;
pub mod utils;
mod glob_defines;
pub mod indices;
pub use self::errors::Error;
pub use self::errors::PdfError;
pub use date::*;
pub use self::errors::IndexError;
pub use rusttype::Error as RusttypeError;
pub use self::scale::{Mm, Pt, Px};
pub use self::types::pdf_conformance::{CustomPdfConformance, PdfConformance};
pub use self::types::pdf_document::{PdfDocumentReference, PdfDocument};
pub use self::types::pdf_metadata::PdfMetadata;
pub use self::types::pdf_page::{PdfPage, PdfPageReference};
pub use self::types::pdf_layer::{PdfLayer, PdfLayerReference};
pub use self::types::plugins::xmp::xmp_metadata::XmpMetadata;
pub use self::types::plugins::misc::document_info::DocumentInfo;
/// Stub module for 3D content in a PDF
pub use self::types::plugins::graphics::three_dimensional;
pub use self::types::plugins::graphics::two_dimensional::font::{
Font, FontData, BuiltinFont, ExternalFont, TextRenderingMode, IndirectFontRef, DirectFontRef, FontList
};
pub use self::types::plugins::graphics::two_dimensional::image::Image;
pub use self::types::plugins::graphics::two_dimensional::line::Line;
pub use self::types::plugins::graphics::two_dimensional::point::Point;
pub use self::types::plugins::graphics::color::{
Color, Rgb, Cmyk, Greyscale, SpotColor, PdfColor, ColorSpace, ColorBits
};
pub use self::types::plugins::graphics::ctm::{CurTransMat, TextMatrix};
pub use self::types::plugins::graphics::extgstate::{
ExtendedGraphicsState, ExtendedGraphicsStateList, ExtendedGraphicsStateRef, ExtendedGraphicsStateBuilder,
OverprintMode, BlackGenerationFunction, BlackGenerationExtraFunction, UnderColorRemovalFunction,
UnderColorRemovalExtraFunction, TransferFunction, TransferExtraFunction, HalftoneType,
SpotFunction, BlendMode, SeperableBlendMode, NonSeperableBlendMode, RenderingIntent, SoftMask,
SoftMaskFunction, LineJoinStyle, LineCapStyle, LineDashPattern,
};
pub use self::types::plugins::graphics::icc_profile::{
IccProfileType, IccProfile, IccProfileRef, IccProfileList
};
pub use self::types::plugins::graphics::ocg::{OCGList, OCGRef};
pub use self::types::plugins::graphics::pattern::{Pattern, PatternRef, PatternList};
pub use self::types::plugins::graphics::pdf_resources::PdfResources;
pub use self::types::plugins::graphics::xobject::{
XObject, XObjectList, XObjectRef, ImageXObject, ImageXObjectRef,
ImageFilter, FormXObject, FormXObjectRef, FormType, SMask, GroupXObject,
GroupXObjectType, ReferenceXObject, OptionalContentGroup, OCGIntent, PostScriptXObject,
};
/// Stub module for future audio embedding implementation
pub use self::types::plugins::media::audio;
/// Stub module for future video embedding implementation
pub use self::types::plugins::media::video;
/// Stub module for interactive (JavaScript) content, embedded in PDF files
pub use self::types::plugins::interactive;
/// Stub module for encryption (passwords). Not implemented yet.
pub use self::types::plugins::security;
+198
View File
@@ -0,0 +1,198 @@
//! Scaling types for reducing errors between conversions between point (pt) and millimeter (mm)
macro_rules! impl_partialeq {
($t:ty) => {
impl PartialEq for $t {
// custom compare function because of floating point inaccuracy
fn eq(&self, other: &$t) -> bool {
if self.0.is_normal() && other.0.is_normal() {
// four floating point numbers have to match
(self.0 * 1000.0).round() == (other.0 * 1000.0).round()
} else {
false
}
}
}
};
}
/// Scale in millimeter
#[derive(Debug, Copy, Clone, PartialOrd)]
pub struct Mm(pub f64);
impl From<Pt> for Mm {
fn from(value: Pt) -> Mm {
Mm(value.0 * 0.352_778_f64)
}
}
impl_partialeq!(Mm);
/// Scale in point
#[derive(Debug, Copy, Clone, PartialOrd)]
pub struct Pt(pub f64);
impl From<Mm> for Pt {
fn from(value: Mm) -> Pt {
Pt(value.0 * 2.834_646_f64)
}
}
impl From<Pt> for ::lopdf::Object {
fn from(value: Pt) -> Self {
Self::Real(value.0)
}
}
impl_partialeq!(Pt);
/// Scale in pixels
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Px(pub usize);
impl Px {
pub fn into_pt(self, dpi: f64) -> Pt {
Mm(self.0 as f64 * (25.4 / dpi)).into()
}
}
use std::ops::{Add, Div, Mul, Sub};
use std::ops::{AddAssign, DivAssign, MulAssign, SubAssign};
macro_rules! impl_add_self {
($type:ident) => {
impl Add for $type {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
0: self.0 + other.0,
}
}
}
};
}
macro_rules! impl_add_assign_self {
($type:ident) => {
impl AddAssign for $type {
fn add_assign(&mut self, other: Self) {
self.0 += other.0;
}
}
};
}
macro_rules! impl_sub_assign_self {
($type:ident) => {
impl SubAssign for $type {
fn sub_assign(&mut self, other: Self) {
self.0 -= other.0;
}
}
};
}
macro_rules! impl_sub_self {
($type:ident) => {
impl Sub for $type {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
0: self.0 - other.0,
}
}
}
};
}
macro_rules! impl_mul_f64 {
($type:ident) => {
impl Mul<f64> for $type {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self { 0: self.0 * other }
}
}
};
}
macro_rules! impl_mul_assign_f64 {
($type:ident) => {
impl MulAssign<f64> for $type {
fn mul_assign(&mut self, other: f64) {
self.0 *= other;
}
}
};
}
macro_rules! impl_div {
($type:ident) => {
impl Div<$type> for $type {
type Output = f64;
fn div(self, other: $type) -> Self::Output {
self.0 / other.0
}
}
impl Div<f64> for $type {
type Output = Self;
fn div(self, other: f64) -> Self::Output {
Self { 0: self.0 / other }
}
}
};
}
macro_rules! impl_div_assign_f64 {
($type:ident) => {
impl DivAssign<f64> for $type {
fn div_assign(&mut self, other: f64) {
self.0 /= other;
}
}
};
}
impl_add_self!(Mm);
impl_add_self!(Pt);
impl_add_self!(Px);
impl_add_assign_self!(Mm);
impl_add_assign_self!(Pt);
impl_add_assign_self!(Px);
impl_sub_assign_self!(Mm);
impl_sub_assign_self!(Pt);
impl_sub_assign_self!(Px);
impl_sub_self!(Mm);
impl_sub_self!(Pt);
impl_sub_self!(Px);
impl_mul_f64!(Mm);
impl_mul_f64!(Pt);
impl_mul_assign_f64!(Mm);
impl_mul_assign_f64!(Pt);
impl_div!(Mm);
impl_div!(Pt);
impl_div_assign_f64!(Mm);
impl_div_assign_f64!(Pt);
#[test]
fn point_to_mm_conversion() {
let pt1: Mm = Pt(1.0).into();
let pt2: Mm = Pt(15.0).into();
assert_eq!(pt1, Mm(0.352778));
assert_eq!(pt2, Mm(5.29167));
}
#[test]
fn mm_to_point_conversion() {
let mm1: Pt = Mm(1.0).into();
let mm2: Pt = Mm(23.0).into();
assert_eq!(mm1, Pt(2.83464745483286));
assert_eq!(mm2, Pt(65.1969));
}
Binary file not shown.
Binary file not shown.
+51
View File
@@ -0,0 +1,51 @@
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c015 84.159810, 2016/09/10-02:41:30 ">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:xmp="http://ns.adobe.com/xap/1.0/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"
xmlns:pdfxid="http://www.npes.org/pdfx/ns/id/"
xmlns:pdfx="http://ns.adobe.com/pdfx/1.3/"
xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
<xmp:CreateDate>{0}</xmp:CreateDate>
<xmp:ModifyDate>{1}</xmp:ModifyDate>
<xmp:MetadataDate>{2}</xmp:MetadataDate>
<dc:format>application/pdf</dc:format>
<dc:title>
<rdf:Alt>
<rdf:li xml:lang="x-default">{3}</rdf:li>
</rdf:Alt>
</dc:title>
<xmpMM:DocumentID>uuid:{4}</xmpMM:DocumentID>
<xmpMM:InstanceID>uuid:{5}</xmpMM:InstanceID>
<xmpMM:RenditionClass>{6}</xmpMM:RenditionClass>
<xmpMM:VersionID>{7}</xmpMM:VersionID>
<pdfxid:GTS_PDFXVersion>{8}</pdfxid:GTS_PDFXVersion>
<pdfx:GTS_PDFXVersion>{8}</pdfx:GTS_PDFXVersion>
<pdf:Trapped>{9}</pdf:Trapped>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
+24
View File
@@ -0,0 +1,24 @@
%!PS-Adobe-3.0 Resource-CMap
%%DocumentNeededResources: ProcSet (CIDInit)
%%IncludeResource: ProcSet (CIDInit)
%%BeginResource: CMap (Adobe-Identity-UCS)
%%Title: (Adobe-Identity-UCS Adobe Identity 0)
%%Version: 1
%%EndComments
/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo 3 dict dup begin
/Registry (Adobe) def
/Ordering (Identity) def
/Supplement 0 def
end def
/CMapName /Adobe-Identity-UCS def
/CMapVersion 1 def
/CMapType 0 def
/WMode 0 def
2 begincodespacerange
<20> <20>
<0000> <FFFF>
endcodespacerange
1469 begincidchar
+8
View File
@@ -0,0 +1,8 @@
<20> 1469
endcidchar
endcmap
CMapName currentdict /CMap defineresource pop
end
end
%%EndResource
%%EOF
+24
View File
@@ -0,0 +1,24 @@
/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
%!PS-Adobe-3.0 Resource-CMap
%%DocumentNeededResources: procset CIDInit
%%IncludeResource: procset CIDInit
/CIDSystemInfo 3 dict dup begin
/Registry (FontSpecific) def
/Ordering ({0}) def
/Supplement 0 def
end def
/CMapName /FontSpecific-{0} def
/CMapVersion 1 def
/CMapType 2 def
/WMode 0 def
1 begincodespacerange
<0000> <FFFF>
endcodespacerange
+4
View File
@@ -0,0 +1,4 @@
endcmap
CMapName currentdict /CMap defineresource pop
end
end
+15
View File
@@ -0,0 +1,15 @@
//! Shared types regarding the structure of a PDF.
pub mod pdf_conformance;
pub mod pdf_document;
pub mod pdf_layer;
pub mod pdf_metadata;
pub mod pdf_page;
pub mod plugins;
pub use self::pdf_document::{PdfDocument, PdfDocumentReference};
pub use self::pdf_layer::{PdfLayer, PdfLayerReference};
pub use self::pdf_page::{PdfPage, PdfPageReference};
pub use self::pdf_conformance::{PdfConformance, CustomPdfConformance};
pub use self::pdf_metadata::PdfMetadata;
pub use self::plugins::*;
+272
View File
@@ -0,0 +1,272 @@
//! Module regulating the comparison and feature sets / allowed plugins of a PDF document
//!
//! NOTE: All credit to Wikipedia:
//!
//! [PDF/X Versions](https://en.wikipedia.org/wiki/PDF/X)
//!
//! [PDF/A Versions](https://en.wikipedia.org/wiki/PDF/A)
/// List of (relevant) PDF versions
/// Please note the difference between **PDF/A** (archiving), **PDF/UA** (universal acessibility),
/// **PDF/X** (printing), **PDF/E** (engineering / CAD), **PDF/VT** (large volume transactions with
/// repeated content)
#[derive(Debug, PartialEq, Eq, Clone)]
#[allow(non_camel_case_types)]
pub enum PdfConformance {
/// `PDF/A-1b` basic PDF, many features restricted
A1B_2005_PDF_1_4,
/// `PDF/A-1a` language specification, hierarchical document structure,
/// character mappings to unicode, descriptive text for images
A1A_2005_PDF_1_4,
/// `PDF/A-2:2011` - JPEG compression, transpareny, layering, OpenType fonts
A2_2011_PDF_1_7,
/// `PDF/A-2a:2011`
A2A_2011_PDF_1_7,
/// `PDF/A-2b:2011`
A2B_2011_PDF_1_7,
/// `PDF/A-2u:2011` - requires all text to be Unicode
A2U_2011_PDF_1_7,
/// `PDF/A-3` - like A2 but with embedded files (XML, CAD, etc.)
A3_2012_PDF_1_7,
/// `PDF/UA-1` extra functions for accessibility (blind, screenreaders, search, dynamic layout)
UA_2014_PDF_1_6,
/// `PDF/X-1a:2001` no ICC profiles
X1A_2001_PDF_1_3,
/// `PDF/X-3:2002` allows CMYK, spot, calibrated (managed) RGB, CIELAB, + ICC Profiles
X3_2002_PDF_1_3,
/// `PDF/X-1a:2003` Revision of `PDF/X-1a:2001` based on PDF 1.4
X1A_2003_PDF_1_4,
/// `PDF/X-3:2003` Revision of `PDF/X-3:2002` based on PDF 1.4
X3_2003_PDF_1_4,
/// `PDF/X-4:2010` Colour-managed, CMYK, gray, RGB or spot colour data are supported
/// as well as PDF transparency and optional content (layers)
X4_2010_PDF_1_4,
/// `PDF/X-4p:2010` Same as the above X-4:2010, but may reference an ICC profile from
/// an external file, and it's based on PDF 1.6
X4P_2010_PDF_1_6,
/// `PDF/X-5g:2010` An extension of PDF/X-4 that enables the use of external graphical
/// content. This can be described as OPI-like (Open Prepress Interface) workflows.
/// Specifically this allows graphics to be referenced that are outside the PDF
X5G_2010_PDF_1_6,
/// `PDF/X-5pg` An extension of PDF/X-4p that enables the use of external graphical
/// content in conjunction with a reference to an external ICC Profile for the output intent.
X5PG_2010_PDF_1_6,
/// `PDF/X-5n` An extension of PDF/X-4p that allows the externally supplied ICC
/// Profile for the output intent to use a color space other than Greyscale, RGB and CMYK.
X5N_2010_PDF_1_6,
/// `PDF/E-1:2008` 3D Objects, geospatial, etc.
E1_2008_PDF_1_6,
/// `PDF/VT-1:2010` Basically a way to make a incomplete PDF as a template and the RIP program
/// is set up in a way that it can easily inject data into the PDF, for high-throughput PDFs
/// (like postcards, stamps), that require customization before printing
VT_2010_PDF_1_4,
/// Custom PDF conformance, to allow / disallow options. This allows for making very small
/// documents, for example
Custom(CustomPdfConformance),
}
/// Allows building custom conformance profiles. This is useful if you want very small documents for example and
/// you don't __need__ conformance with any PDF standard, you just want a PDF file.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CustomPdfConformance {
/// Identifier for this conformance
///
/// Default: __""__
pub identifier: String,
/// Does this standard allow 3d content?
///
/// Default: __false__
pub allows_3d_content: bool,
/// Does this standard allow video content?
///
/// Default: __false__
pub allows_video_content: bool,
/// Does this standard allow audio content
///
/// Default: __false__
pub allows_audio_content: bool,
/// Does this standard allow enbedded JS?
///
/// Default: __false__
pub allows_embedded_javascript: bool,
/// Does this standard allow enbedding JPEG files?
///
/// Default: __true__
pub allows_jpeg_content: bool,
/// Does this standard require XMP metadata to be set?
///
/// Default: __true__
pub requires_xmp_metadata: bool,
/// Does this standard allow the default PDF fonts (Helvetica, etc.)
///
/// _(please don't enable this if you do any work that has to be printed accurately)_
///
/// Default: __false__
pub allows_default_fonts: bool,
/// Does this standard require an ICC profile to be embedded for color management?
///
/// Default: __true__
pub requires_icc_profile: bool,
/// Does this standard allow PDF layers?
///
/// Default: __true__
pub allows_pdf_layers: bool,
}
impl Default for CustomPdfConformance {
fn default() -> Self {
CustomPdfConformance {
identifier: "".into(),
allows_3d_content: false,
allows_video_content: false,
allows_audio_content: false,
allows_embedded_javascript: false,
allows_jpeg_content: true,
requires_xmp_metadata: false,
allows_default_fonts: false,
requires_icc_profile: false,
allows_pdf_layers: true,
}
}
}
impl PdfConformance {
/// Get the identifier string for PDF
pub fn get_identifier_string(&self)
-> String
{
// todo: these identifiers might not be correct in all cases
let identifier = match *self {
PdfConformance::A1B_2005_PDF_1_4 => "PDF/A-1b:2005",
PdfConformance::A1A_2005_PDF_1_4 => "PDF/A-1a:2005",
PdfConformance::A2_2011_PDF_1_7 => "PDF/A-2:2011",
PdfConformance::A2A_2011_PDF_1_7 => "PDF/A-2a:2011",
PdfConformance::A2B_2011_PDF_1_7 => "PDF/A-2b:2011",
PdfConformance::A2U_2011_PDF_1_7 => "PDF/A-2u:2011",
PdfConformance::A3_2012_PDF_1_7 => "PDF/A-3:2012",
PdfConformance::UA_2014_PDF_1_6 => "PDF/UA",
PdfConformance::X1A_2001_PDF_1_3 => "PDF/X-1a:2001",
PdfConformance::X3_2002_PDF_1_3 => "PDF/X-3:2002",
PdfConformance::X1A_2003_PDF_1_4 => "PDF/X-1a:2003",
PdfConformance::X3_2003_PDF_1_4 => "PDF/X-3:2003",
PdfConformance::X4_2010_PDF_1_4 => "PDF/X-4",
PdfConformance::X4P_2010_PDF_1_6 => "PDF/X-4P",
PdfConformance::X5G_2010_PDF_1_6 => "PDF/X-5G",
PdfConformance::X5PG_2010_PDF_1_6 => "PDF/X-5PG",
PdfConformance::X5N_2010_PDF_1_6 => "PDF/X-5N",
PdfConformance::E1_2008_PDF_1_6 => "PDF/E-1",
PdfConformance::VT_2010_PDF_1_4 => "PDF/VT",
PdfConformance::Custom(ref c) => &c.identifier,
};
identifier.to_string()
}
/// __STUB__: Detects if the PDF has 3D content, but the
/// conformance to the given PDF standard does not allow it.
pub fn is_3d_content_allowed(&self)
-> bool
{
match *self {
PdfConformance::E1_2008_PDF_1_6 => true,
PdfConformance::Custom(ref c) => c.allows_3d_content,
_ => false,
}
}
/// Does this conformance level allow video
pub fn is_video_content_allowed(&self)
-> bool
{
// todo
match *self {
PdfConformance::Custom(ref c) => c.allows_video_content,
_ => false,
}
}
/// __STUB__: Detects if the PDF has audio content, but the
/// conformance to the given PDF standard does not allow it.
pub fn is_audio_content_allowed(&self)
-> bool
{
// todo
match *self {
PdfConformance::Custom(ref c) => c.allows_audio_content,
_ => false,
}
}
/// __STUB__: Detects if the PDF has 3D content, but the
/// conformance to the given PDF standard does not allow it.
pub fn is_javascript_content_allowed(&self)
-> bool
{
// todo
match *self {
PdfConformance::Custom(ref c) => c.allows_embedded_javascript,
_ => false,
}
}
/// __STUB__: Detects if the PDF has JPEG images, but the
/// conformance to the given PDF standard does not allow it
pub fn is_jpeg_content_allowed(&self)
-> bool
{
// todo
match *self {
PdfConformance::Custom(ref c) => c.allows_jpeg_content,
_ => true,
}
}
/// Detects if the PDF must have XMP metadata
/// if it has to conform to the given PDF Standard
#[cfg_attr(feature = "cargo-clippy", allow(match_same_arms))]
pub fn must_have_xmp_metadata(&self)
-> bool
{
match *self {
PdfConformance::X1A_2001_PDF_1_3 => { true },
PdfConformance::X3_2002_PDF_1_3 => { true },
PdfConformance::X1A_2003_PDF_1_4 => { true },
PdfConformance::X3_2003_PDF_1_4 => { true },
PdfConformance::X4_2010_PDF_1_4 => { true },
PdfConformance::X4P_2010_PDF_1_6 => { true },
PdfConformance::X5G_2010_PDF_1_6 => { true },
PdfConformance::X5PG_2010_PDF_1_6 => { true },
PdfConformance::Custom(ref c) => { c.requires_xmp_metadata }
_ => { false },
}
}
/// Check if the conformance level must have an ICC Profile
pub fn must_have_icc_profile(&self)
-> bool
{
// todo
match *self {
PdfConformance::X1A_2001_PDF_1_3 => { false },
PdfConformance::Custom(ref c) => { c.requires_icc_profile }
_ => { true },
}
}
/// __STUB__: Detects if the PDF has layering (optional content groups),
/// but the conformance to the given PDF standard does not allow it.
#[cfg_attr(feature = "cargo-clippy", allow(match_same_arms))]
pub fn is_layering_allowed(&self)
-> bool
{
match *self {
PdfConformance::X1A_2001_PDF_1_3 => { false },
PdfConformance::X3_2002_PDF_1_3 => { false },
PdfConformance::X1A_2003_PDF_1_4 => { false },
PdfConformance::X3_2003_PDF_1_4 => { false },
PdfConformance::Custom(ref c) => { c.allows_pdf_layers }
_ => { true },
}
}
}
+659
View File
@@ -0,0 +1,659 @@
//! A `PDFDocument` represents the whole content of the file
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::BufWriter;
use std::io::Write;
use std::rc::Rc;
use utils::random_character_string_32;
use crate::OffsetDateTime;
use lopdf;
use indices::*;
use {
ExternalFont, Font, PdfPage, FontList, IccProfileList, PdfMetadata, PdfConformance, IndirectFontRef,
DirectFontRef, BuiltinFont, PdfPageReference, Error, Mm, FontData
};
/// PDF document
#[derive(Debug, Clone)]
pub struct PdfDocument {
/// Pages of the document
pub(super) pages: Vec<PdfPage>,
/// Fonts used in this document
pub fonts: FontList,
/// ICC profiles used in the document
pub(super) icc_profiles: IccProfileList,
/// Inner PDF document
pub(super) inner_doc: lopdf::Document,
/// Document ID. Must be changed if the document is loaded / parsed from a file
pub document_id: String,
/// Metadata for this document
pub metadata: PdfMetadata,
/// The bookmarks in the document. A HashMap<Page Number, Bookmark Name>
pub bookmarks: HashMap<usize, String>,
}
/// Marker struct for a document. Used to make the API a bit nicer.
/// It simply calls `PdfDocument` functions.
pub struct PdfDocumentReference {
/// A wrapper for a document, so actions from outside this library
/// are restricted to functions inside this crate (only functions in `lopdf`
/// can directly manipulate the document)
pub(crate) document: Rc<RefCell<PdfDocument>>,
}
impl PdfDocument {
/// Creates a new PDF document
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(new_ret_no_self))]
pub fn new<S1, S2>(
document_title: S1,
initial_page_width: Mm,
initial_page_height: Mm,
initial_layer_name: S2,
) -> (PdfDocumentReference, PdfPageIndex, PdfLayerIndex)
where S1: Into<String>, S2: Into<String>
{
let doc = Self {
pages: Vec::new(),
document_id: random_character_string_32(),
fonts: FontList::new(),
icc_profiles: IccProfileList::new(),
inner_doc: lopdf::Document::with_version("1.3"),
metadata: PdfMetadata::new(document_title, 1, false, PdfConformance::X3_2002_PDF_1_3),
bookmarks: HashMap::new(),
};
let doc_ref = Rc::new(RefCell::new(doc));
let (initial_page, layer_index) = PdfPage::new(
initial_page_width,
initial_page_height,
initial_layer_name,
0);
{ doc_ref.borrow_mut().pages.push(initial_page); }
(PdfDocumentReference { document: doc_ref }, PdfPageIndex(0), layer_index)
}
pub fn empty<S: Into<String>>(document_title: S) -> PdfDocumentReference {
let doc = Self {
pages: Vec::new(),
document_id: random_character_string_32(),
fonts: FontList::new(),
icc_profiles: IccProfileList::new(),
inner_doc: lopdf::Document::with_version("1.3"),
metadata: PdfMetadata::new(document_title, 1, false, PdfConformance::X3_2002_PDF_1_3),
bookmarks: HashMap::new(),
};
let doc_ref = Rc::new(RefCell::new(doc));
PdfDocumentReference { document: doc_ref }
}
}
macro_rules! implement_adding_fonts {
($self:expr, $font_name:expr, $font:expr) => {{
let font_ref;
let possible_ref = {
let doc = $self.document.borrow();
font_ref = IndirectFontRef::new($font_name);
match doc.fonts.get_font(&font_ref) {
Some(f) => Some(f.clone()),
None => None,
}
};
if possible_ref.is_some() {
Ok(font_ref)
} else {
let mut doc = $self.document.borrow_mut();
let direct_ref = DirectFontRef {
inner_obj: doc.inner_doc.new_object_id(),
data: $font
};
doc.fonts.add_font(font_ref.clone(), direct_ref);
Ok(font_ref)
}
}}
}
impl PdfDocumentReference {
// ----- BUILDER FUNCTIONS
/// Changes the title on both the document info dictionary as well as the metadata
#[inline]
pub fn with_title<S>(self, new_title: S)
-> () where S: Into<String>
{
self.document.borrow_mut().metadata.document_title = new_title.into();
}
/// Set the trapping of the document
#[inline]
pub fn with_trapping(self, trapping: bool)
-> Self
{
self.document.borrow_mut().metadata.trapping = trapping;
self
}
/// Sets the document ID (for comparing two PDF documents for equality)
#[inline]
pub fn with_document_id(self, id: String)
-> Self
{
self.document.borrow_mut().metadata.xmp_metadata.document_id = id;
self
}
/// Set the version of the document
#[inline]
pub fn with_document_version(self, version: u32)
-> Self
{
self.document.borrow_mut().metadata.document_version = version;
self
}
/// Changes the conformance of this document. It is recommended to call
/// `check_for_errors()` after changing it.
#[inline]
pub fn with_conformance(self, conformance: PdfConformance)
-> Self
{
self.document.borrow_mut().metadata.conformance = conformance;
self
}
/// Sets the creation date on the document.
///
/// Per default, the creation date is set to the current time.
#[inline]
pub fn with_creation_date(self, creation_date: OffsetDateTime)
-> Self
{
self.document.borrow_mut().metadata.creation_date = creation_date;
self
}
/// Sets the modification date on the document. Intended to be used when
/// reading documents that already have a modification date.
#[inline]
pub fn with_mod_date(self, mod_date: OffsetDateTime)
-> Self
{
self.document.borrow_mut().metadata.modification_date = mod_date;
self
}
// ----- ADD FUNCTIONS
/// Create a new pdf page and returns the index of the page
#[inline]
pub fn add_page<S>(
&self,
x_mm: Mm,
y_mm: Mm,
inital_layer_name: S,
) -> (PdfPageIndex, PdfLayerIndex)
where
S: Into<String>,
{
let mut doc = self.document.borrow_mut();
let (pdf_page, pdf_layer_index) =
PdfPage::new(x_mm, y_mm, inital_layer_name, doc.pages.len());
doc.pages.push(pdf_page);
let page_index = PdfPageIndex(doc.pages.len() - 1);
(page_index, pdf_layer_index)
}
/// Create a new pdf page and returns the index of the page.
/// If the page already has a bookmark, overwrites it.
#[inline]
pub fn add_bookmark<S>(&self, name: S, page: PdfPageIndex)
where
S: Into<String>,
{
let mut doc = self.document.borrow_mut();
doc.bookmarks.insert(page.0, name.into());
}
/// Add a font from a font stream
pub fn add_external_font<R>(
&self,
font_stream: R,
) -> ::std::result::Result<IndirectFontRef, Error>
where
R: ::std::io::Read,
{
let last_font_index = {
let doc = self.document.borrow();
doc.fonts.len()
};
let external_font = ExternalFont::new(font_stream, last_font_index)?;
let external_font_name = external_font.face_name.clone();
let font = Font::ExternalFont(external_font);
implement_adding_fonts!(&self, external_font_name, font)
}
/// Add a font from a custom font backend
pub fn add_external_font_data<F>(&self, bytes: Vec<u8>, data: F)
-> ::std::result::Result<IndirectFontRef, Error>
where
F: FontData + 'static,
{
let last_font_index = { let doc = self.document.borrow(); doc.fonts.len() };
let external_font = ExternalFont::with_font_data(bytes, last_font_index, Box::new(data));
let external_font_name = external_font.face_name.clone();
let font = Font::ExternalFont(external_font);
implement_adding_fonts!(&self, external_font_name, font)
}
/// Add a built-in font to the document
///
/// Built-in fonts can only be used to print characters that are supported by the
/// [Windows-1252][] encoding. All other characters will be ignored.
///
/// [Windows-1252]: https://en.wikipedia.org/wiki/Windows-1252
pub fn add_builtin_font(&self, builtin_font: BuiltinFont)
-> ::std::result::Result<IndirectFontRef, Error>
{
let builtin_font_name: &'static str = builtin_font.clone().into();
implement_adding_fonts!(&self, builtin_font_name, Font::BuiltinFont(builtin_font))
}
// ----- GET FUNCTIONS
/// Returns the page (for inserting content)
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(unnecessary_operation))]
pub fn get_page(&self, page: PdfPageIndex)
-> PdfPageReference
{
&self.document.borrow_mut().pages[page.0];
PdfPageReference { document: Rc::downgrade(&self.document).clone(), page }
}
/// Returns a direct reference (object ID) to the font from an
/// indirect reference (postscript name)
#[inline]
pub fn get_font(&self, font: &IndirectFontRef)
-> Option<DirectFontRef>
{
let doc = self.document.borrow();
doc.fonts.get_font(font)
}
/// Drops the PDFDocument, returning the inner `lopdf::Document`.
/// Document may be only half-written, use only in extreme cases
#[inline]
pub unsafe fn get_inner(self)
-> lopdf::Document
{
let doc = Rc::try_unwrap(self.document).unwrap().into_inner();
doc.inner_doc
}
// --- MISC FUNCTIONS
/// Checks for invalid settings in the document
pub fn check_for_errors(&self)
-> ::std::result::Result<(), Error>
{
// TODO
#[cfg(feature = "logging")] {
warn!("Checking PDFs for errors is currently not supported!");
}
Ok(())
}
/// Tries to match the document to the given conformance.
/// Errors only on an unrecoverable error.
pub fn repair_errors(&self, _conformance: PdfConformance)
-> ::std::result::Result<(), Error>
{
// TODO
#[cfg(feature = "logging")] {
warn!("Reparing PDFs is currently not supported!");
}
Ok(())
}
/// Save PDF Document, writing the contents to the target
pub fn save<W: Write>(self, target: &mut BufWriter<W>) -> ::std::result::Result<(), Error> {
use lopdf::Object::*;
use lopdf::StringFormat::Literal;
use lopdf::{Dictionary as LoDictionary, Object as LoObject};
use std::iter::FromIterator;
// todo: remove unwrap, handle error
let mut doc = Rc::try_unwrap(self.document).unwrap().into_inner();
let pages_id = doc.inner_doc.new_object_id();
let bookmarks_id = doc.inner_doc.new_object_id();
let mut bookmarks_list = LoDictionary::from_iter(vec![
("Type", "Outlines".into()),
("Count", Integer(doc.bookmarks.len() as i64)),
/* First and Last will be filled in once they are created from the pages */
]);
// extra pdf infos
let (xmp_metadata, document_info, icc_profile) = doc.metadata.clone().into_obj();
let xmp_metadata_id = match xmp_metadata {
Some(metadata) => Some(doc.inner_doc.add_object(metadata)),
None => None,
};
let document_info_id = doc.inner_doc.add_object(document_info);
// add catalog
let icc_profile_descr = "Commercial and special offset print acccording to ISO \
12647-2:2004 / Amd 1, paper type 1 or 2 (matte or gloss-coated \
offset paper, 115 g/m2), screen ruling 60/cm";
let icc_profile_str = "Coated FOGRA39 (ISO 12647-2:2004)";
let icc_profile_short = "FOGRA39";
let mut output_intents = LoDictionary::from_iter(vec![
("S", Name("GTS_PDFX".into())),
("OutputCondition", String(icc_profile_descr.into(), Literal)),
("Type", Name("OutputIntent".into())),
(
"OutputConditionIdentifier",
String(icc_profile_short.into(), Literal),
),
(
"RegistryName",
String("http://www.color.org".into(), Literal),
),
("Info", String(icc_profile_str.into(), Literal)),
]);
let mut catalog = LoDictionary::from_iter(vec![
("Type", "Catalog".into()),
("PageLayout", "OneColumn".into()),
(
"PageMode",
if doc.bookmarks.len() > 0 {
"UseOutlines"
} else {
"UseNone"
}
.into(),
),
("Outlines", Reference(bookmarks_id)),
("Pages", Reference(pages_id)),
]);
if let Some(profile) = icc_profile {
let icc_profile: lopdf::Stream = profile.into();
let icc_profile_id = doc.inner_doc.add_object(Stream(icc_profile));
output_intents.set("DestinationOutputProfile", Reference(icc_profile_id));
catalog.set("OutputIntents", Array(vec![Dictionary(output_intents)]));
}
if let Some(metadata_id) = xmp_metadata_id {
catalog.set("Metadata", Reference(metadata_id));
}
let mut pages = LoDictionary::from_iter(vec![
("Type", "Pages".into()),
("Count", Integer(doc.pages.len() as i64)),
/* Kids and Resources missing */
]);
// add all pages with contents
let mut page_ids = Vec::<LoObject>::new();
// ----- OCG CONTENT
// page index + page names to add the OCG to the /Catalog
let page_layer_names: Vec<(usize, Vec<::std::string::String>)> =
doc.pages.iter().map(|page|
(page.index, page.layers.iter().map(|layer|
layer.name.clone()).collect()
)).collect();
// add optional content groups (layers) to the /Catalog
let usage_ocg_dict = LoDictionary::from_iter(vec![
("Type", Name("OCG".into())),
("CreatorInfo", Dictionary(LoDictionary::from_iter(vec![
("Creator", String("Adobe Illustrator 14.0".into(), Literal)),
("Subtype", Name("Artwork".into()))
]))),
]);
let usage_ocg_dict_ref = doc.inner_doc.add_object(Dictionary(usage_ocg_dict));
let intent_arr = Array(vec![
Name("View".into()),
Name("Design".into()),
]);
let intent_arr_ref = doc.inner_doc.add_object(intent_arr);
// page index, layer index, reference to OCG dictionary
let ocg_list: Vec<(usize, Vec<(usize, lopdf::Object)>)> =
page_layer_names.into_iter().map(|(page_idx, layer_names)|
(page_idx,
layer_names.into_iter().enumerate().map(|(layer_idx, layer_name)|
(layer_idx,
Reference(doc.inner_doc.add_object(
Dictionary(LoDictionary::from_iter(vec![
("Type", Name("OCG".into())),
("Name", String(layer_name.into(), Literal)),
("Intent", Reference(intent_arr_ref)),
("Usage", Reference(usage_ocg_dict_ref))
]))
)))
).collect()))
.collect();
let flattened_ocg_list: Vec<lopdf::Object> =
ocg_list.iter().flat_map(|&(_, ref layers)|
layers.iter().map(|&(_, ref obj)| obj.clone())
).collect();
catalog.set("OCProperties", Dictionary(LoDictionary::from_iter(vec![
("OCGs", Array(flattened_ocg_list.clone())),
// optional content configuration dictionary, page 376
("D", Dictionary(LoDictionary::from_iter(vec![
("Order", Array(flattened_ocg_list.clone())),
// "radio button groups"
("RBGroups", Array(vec![])),
// initially visible OCG
("ON", Array(flattened_ocg_list)),
])))
])));
// ----- END OCG CONTENT (on document level)
// ----- PAGE CONTENT
// add fonts (shared resources)
let mut font_dict_id = None;
// add all fonts / other resources shared in the whole document
let fonts_dict: lopdf::Dictionary = doc.fonts.into_with_document(&mut doc.inner_doc);
if fonts_dict.len() > 0 {
font_dict_id = Some(doc.inner_doc.add_object(Dictionary(fonts_dict)));
}
let mut page_id_to_obj: HashMap<usize, (u32, u16)> = HashMap::new();
for (idx, page) in doc.pages.into_iter().enumerate() {
let mut p = LoDictionary::from_iter(vec![
("Type", "Page".into()),
("Rotate", Integer(0)),
(
"MediaBox",
vec![0.into(), 0.into(), page.width.into(), page.height.into()].into(),
),
(
"TrimBox",
vec![0.into(), 0.into(), page.width.into(), page.height.into()].into(),
),
(
"CropBox",
vec![0.into(), 0.into(), page.width.into(), page.height.into()].into(),
),
("Parent", Reference(pages_id)),
]);
// this will collect the resources needed for rendering this page
let layers_temp = ocg_list.iter().find(|e| e.0 == idx).unwrap();
let (mut resources_page, layer_streams) =
page.collect_resources_and_streams(&mut doc.inner_doc, &layers_temp.1);
if let Some(f) = font_dict_id {
resources_page.set("Font", Reference(f));
}
if resources_page.len() > 0 {
let resources_page_id = doc.inner_doc.add_object(Dictionary(resources_page));
p.set("Resources", Reference(resources_page_id));
}
// merge all streams of the individual layers into one big stream
let mut layer_streams_merged_vec = Vec::<u8>::new();
for mut stream in layer_streams {
layer_streams_merged_vec.append(&mut stream.content);
}
let merged_layer_stream =
lopdf::Stream::new(lopdf::Dictionary::new(), layer_streams_merged_vec)
.with_compression(false);
let page_content_id = doc.inner_doc.add_object(merged_layer_stream);
p.set("Contents", Reference(page_content_id));
let page_obj = doc.inner_doc.add_object(p);
if doc.bookmarks.len() > 0 {
if let Some(_) = doc.bookmarks.get(&idx) {
page_id_to_obj.insert(idx, page_obj);
}
}
page_ids.push(Reference(page_obj))
}
if doc.bookmarks.len() > 0 {
let len = doc.bookmarks.len();
if len == 1 {
let page_index = doc.bookmarks.iter().next().unwrap().0.to_owned();
let title = doc.bookmarks.iter().next().unwrap().1.to_owned();
let obj_ref = doc
.inner_doc
.add_object(Dictionary(LoDictionary::from_iter(vec![
("Parent", Reference(bookmarks_id)),
("Title", String(title.into(), Literal)),
(
"Dest",
Array(vec![
Reference(page_id_to_obj.get(&page_index).unwrap().to_owned()),
"XYZ".into(),
Null,
Null,
Null,
]),
),
])));
bookmarks_list.set("First", Reference(obj_ref));
bookmarks_list.set("Last", Reference(obj_ref));
} else {
let mut sorted_bmarks: Vec<(&usize, &std::string::String)> = doc.bookmarks.iter().collect();
sorted_bmarks.sort();
for (i, (page_index, b_name)) in sorted_bmarks.iter().enumerate() {
let dest = (
"Dest",
Array(vec![
Reference(page_id_to_obj.get(page_index).unwrap().to_owned()),
"XYZ".into(),
Null,
Null,
Null,
]),
);
doc.inner_doc
.add_object(Dictionary(LoDictionary::from_iter(if i == 0 {
bookmarks_list.set("First", Reference((doc.inner_doc.max_id + 1, 0)));
vec![
("Parent", Reference(bookmarks_id)),
("Title", String(b_name.to_owned().to_owned().into(), Literal)),
("Next", Reference((doc.inner_doc.max_id + 2, 0))),
dest,
]
} else if i == len - 1 {
bookmarks_list.set("Last", Reference((doc.inner_doc.max_id + 1, 0)));
vec![
("Parent", Reference(bookmarks_id)),
("Title", String(b_name.to_owned().to_owned().into(), Literal)),
("Prev", Reference((doc.inner_doc.max_id, 0))),
dest,
]
} else {
vec![
("Parent", Reference(bookmarks_id)),
("Title", String(b_name.to_owned().to_owned().into(), Literal)),
("Prev", Reference((doc.inner_doc.max_id, 0))),
("Next", Reference((doc.inner_doc.max_id + 2, 0))),
dest,
]
})));
}
}
}
pages.set::<_, LoObject>("Kids".to_string(), page_ids.into());
// ----- END PAGE CONTENT
doc.inner_doc.objects.insert(pages_id, Dictionary(pages));
doc.inner_doc
.objects
.insert(bookmarks_id, Dictionary(bookmarks_list));
// save inner document
let catalog_id = doc.inner_doc.add_object(catalog);
let instance_id = random_character_string_32();
doc.inner_doc.trailer.set("Root", Reference(catalog_id));
doc.inner_doc
.trailer
.set("Info", Reference(document_info_id));
doc.inner_doc.trailer.set(
"ID",
Array(vec![
String(doc.document_id.as_bytes().to_vec(), Literal),
String(instance_id.as_bytes().to_vec(), Literal),
]),
);
// does nothing in debug mode, optimized in release mode
Self::optimize(&mut doc.inner_doc);
doc.inner_doc.save_to(target)?;
Ok(())
}
#[cfg(any(debug_assertions, feature="less-optimization"))]
#[inline]
fn optimize(_: &mut lopdf::Document) { }
#[cfg(all(not(debug_assertions), not(feature="less-optimization")))]
#[inline]
fn optimize(doc: &mut lopdf::Document)
{
doc.prune_objects();
doc.delete_zero_length_streams();
doc.compress();
}
}
+563
View File
@@ -0,0 +1,563 @@
//! PDF layer management. Layers can contain referenced or real content.
use lopdf;
use indices::{PdfPageIndex, PdfLayerIndex};
use std::rc::Weak;
use std::cell::RefCell;
use lopdf::content::Operation;
use glob_defines::OP_PATH_STATE_SET_LINE_WIDTH;
use {
Font, XObject, PdfColor, PdfDocument, ExtendedGraphicsStateBuilder, Line, ImageXObject, XObjectRef, Color, IndirectFontRef, BlendMode,
LineJoinStyle, LineCapStyle, LineDashPattern, CurTransMat, TextMatrix, TextRenderingMode, Mm, Pt
};
/// One layer of PDF data
#[derive(Debug, Clone)]
pub struct PdfLayer {
/// Name of the layer. Must be present for the optional content group
pub(crate) name: String,
/// Stream objects in this layer. Usually, one layer == one stream
pub(super) operations: Vec<Operation>,
}
/// A "reference" to the current layer, allows for inner mutability
/// but only inside this library
#[derive(Debug, Clone)]
pub struct PdfLayerReference {
/// A weak reference to the document, for inner mutability
pub document: Weak<RefCell<PdfDocument>>,
/// The index of the page this layer is on
pub page: PdfPageIndex,
/// The index of the layer this layer has (inside the page)
pub layer: PdfLayerIndex,
}
impl PdfLayer {
/// Create a new layer, with a name and what index the layer has in the page
#[inline]
pub fn new<S>(name: S)
-> Self where S: Into<String>
{
Self {
name: name.into(),
operations: Vec::new(),
}
}
}
impl Into<lopdf::Stream> for PdfLayer {
fn into(self)
-> lopdf::Stream
{
use lopdf::{Stream, Dictionary};
let stream_content = lopdf::content::Content { operations: self.operations };
// page contents may not be compressed (todo: is this valid for XObjects?)
Stream::new(Dictionary::new(), stream_content.encode().unwrap()).with_compression(false)
}
}
impl PdfLayerReference {
/// Add a shape to the layer. Use `closed` to indicate whether the line is a closed line
/// Use has_fill to determine if the line should be filled.
pub fn add_shape(&self, line: Line)
{
let line_ops = line.into_stream_op();
for op in line_ops {
self.internal_add_operation(op);
}
}
/// Add an image to the layer
/// To be called from the `image.add_to_layer()` class (see `use_xobject` documentation)
pub(crate) fn add_image<T>(&self, image: T)
-> XObjectRef where T: Into<ImageXObject>
{
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page_mut = &mut doc.pages[self.page.0];
page_mut.add_xobject(XObject::Image(image.into()))
}
/*
/// Add an svg element to the layer
/// To be called from the `svg.add_to_layer()` class (see `use_xobject` documentation)
pub(crate) fn add_svg(&self, svg: Svg)
-> std::result::Result<XObjectRef, ::std::io::Error>
{
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page_mut = &mut doc.pages[self.page.0];
let form_data = svg.try_into()?;
Ok(page_mut.add_xobject(XObject::Form(Box::new(form_data))))
}
*/
/// Begins a new text section
/// You have to make sure to call `end_text_section` afterwards
#[inline]
pub fn begin_text_section(&self)
-> ()
{
self.internal_add_operation(Operation::new("BT", vec![] ));
}
/// Ends a new text section
/// Only valid if `begin_text_section` has been called
#[inline]
pub fn end_text_section(&self)
-> ()
{
self.internal_add_operation(Operation::new("ET", vec![] ));
}
/// Set the current fill color for the layer
#[inline]
pub fn set_fill_color(&self, fill_color: Color)
-> ()
{
self.internal_add_operation(PdfColor::FillColor(fill_color));
}
/// Set the current font, only valid in a `begin_text_section` to
/// `end_text_section` block
#[inline]
pub fn set_font(&self, font: &IndirectFontRef, font_size: f64)
-> ()
{
self.internal_add_operation(Operation::new("Tf",
vec![font.name.clone().into(), (font_size).into()]
));
}
/// Set the current line / outline color for the layer
#[inline]
pub fn set_outline_color(&self, color: Color)
{
self.internal_add_operation(PdfColor::OutlineColor(color));
}
/// Instantiate layers, forms and postscript items on the page
/// __WARNING__: Object must be added to the same page, since the XObjectRef is just a
/// String, essentially, it can't be checked that this is the case. The caller is
/// responsible for ensuring this. However, you can use the `Image` struct
/// and use `image.add_to(layer)`, which will essentially do the same thing, but ensures
/// that the image is referenced correctly
///
/// Function is limited to this library to ensure that outside code cannot call it
pub(crate) fn use_xobject(&self, xobj: XObjectRef,
translate_x: Option<Mm>, translate_y: Option<Mm>,
rotate_cw: Option<f64>,
scale_x: Option<f64>, scale_y: Option<f64>)
{
// save graphics state
self.save_graphics_state();
// apply ctm if any
let (mut t_x, mut t_y) = (Mm(0.0), Mm(0.0));
let (mut s_x, mut s_y) = (0.0, 0.0);
if let Some(tr_x) = translate_x { t_x = tr_x; }
if let Some(tr_y) = translate_y { t_y = tr_y; }
if let Some(sc_x) = scale_x { s_x = sc_x; }
if let Some(sc_y) = scale_y { s_y = sc_y; }
// translate, rotate, scale - order does not matter
if t_x != Mm(0.0) || t_y != Mm(0.0) {
let translate_ctm = CurTransMat::Translate(t_x, t_y);
self.internal_add_operation(translate_ctm);
}
if let Some(rot) = rotate_cw {
let rotate_ctm = CurTransMat::Rotate(rot);
self.internal_add_operation(rotate_ctm);
}
if s_x != 0.0 || s_y != 0.0 {
let scale_ctm = CurTransMat::Scale(s_x, s_y);
self.internal_add_operation(scale_ctm);
}
// invoke object
self.internal_invoke_xobject(xobj.name);
// restore graphics state
self.restore_graphics_state();
}
/// Set the overprint mode of the stroke color to true (overprint) or false (no overprint)
pub fn set_overprint_fill(&self, overprint: bool)
{
let new_overprint_state = ExtendedGraphicsStateBuilder::new()
.with_overprint_fill(overprint)
.build();
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page_mut = &mut doc.pages[self.page.0];
let new_ref = page_mut.add_graphics_state(new_overprint_state);
// add gs operator to stream
page_mut.layers[self.layer.0]
.operations.push(lopdf::content::Operation::new(
"gs", vec![lopdf::Object::Name(new_ref.gs_name.as_bytes().to_vec())]
));
}
/// Set the overprint mode of the fill color to true (overprint) or false (no overprint)
/// This changes the graphics state of the current page, don't do it too often or you'll bloat the file size
pub fn set_overprint_stroke(&self, overprint: bool)
{
// this is technically an operation on the page level
let new_overprint_state = ExtendedGraphicsStateBuilder::new()
.with_overprint_stroke(overprint)
.build();
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page_mut = &mut doc.pages[self.page.0];
let new_ref = page_mut.add_graphics_state(new_overprint_state);
page_mut.layers[self.layer.0]
.operations.push(lopdf::content::Operation::new(
"gs", vec![lopdf::Object::Name(new_ref.gs_name.as_bytes().to_vec())]
));
}
/// Set the overprint mode of the fill color to true (overprint) or false (no overprint)
/// This changes the graphics state of the current page, don't do it too often or you'll bloat the file size
pub fn set_blend_mode(&self, blend_mode: BlendMode)
{
// this is technically an operation on the page level
let new_blend_mode_state = ExtendedGraphicsStateBuilder::new()
.with_blend_mode(blend_mode)
.build();
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page_mut = &mut doc.pages[self.page.0];
let new_ref = page_mut.add_graphics_state(new_blend_mode_state);
page_mut.layers[self.layer.0]
.operations.push(lopdf::content::Operation::new(
"gs", vec![lopdf::Object::Name(new_ref.gs_name.as_bytes().to_vec())]
));
}
/// Set the current line thickness, in points
///
/// __NOTE__: 0.0 is a special value, it does not make the line disappear, but rather
/// makes it appear 1px wide across all devices
#[inline]
pub fn set_outline_thickness(&self, outline_thickness: f64)
{
use lopdf::Object::*;
self.internal_add_operation(Operation::new(OP_PATH_STATE_SET_LINE_WIDTH, vec![Real(outline_thickness)]));
}
/// Set the current line join style for outlines
#[inline]
pub fn set_line_join_style(&self, line_join: LineJoinStyle) {
self.internal_add_operation(line_join);
}
/// Set the current line join style for outlines
#[inline]
pub fn set_line_cap_style(&self, line_cap: LineCapStyle) {
self.internal_add_operation(line_cap);
}
/// Set the current line join style for outlines
#[inline]
pub fn set_line_dash_pattern(&self, dash_pattern: LineDashPattern) {
self.internal_add_operation(dash_pattern);
}
/// Sets (adds to) the current transformation matrix
/// Use `save_graphics_state()` and `restore_graphics_state()`
/// to "scope" the transformation matrix to a specific function
#[inline]
pub fn set_ctm(&self, ctm: CurTransMat) {
self.internal_add_operation(ctm);
}
/// Sets (replaces) the current text matrix
/// This does not have to be scoped, since the matrix is replaced
/// instead of concatenated to the current matrix. However,
/// you should only call this function with in a block scoped by
/// `begin_text_section()` and `end_text_section()`
#[inline]
pub fn set_text_matrix(&self, tm: TextMatrix) {
self.internal_add_operation(tm);
}
/// Sets the position where the text should appear
#[inline]
pub fn set_text_cursor(&self, x:Mm, y:Mm) {
let x_in_pt: Pt = x.into();
let y_in_pt: Pt = y.into();
self.internal_add_operation(Operation::new("Td",
vec![x_in_pt.into(), y_in_pt.into()]
));
}
/// If called inside a text block scoped by `begin_text_section` and
/// `end_text_section`, moves the cursor to a new line. PDF does not have
/// any concept of "alignment" except left-aligned text
/// __Note:__ Use `set_line_height` earlier to set the line height first
#[inline]
pub fn add_line_break(&self) {
self.internal_add_operation(Operation::new("T*", Vec::new()));
}
/// Sets the text line height inside a text block
/// (must be called within `begin_text_block` and `end_text_block`)
#[inline]
pub fn set_line_height(&self, height: f64) {
self.internal_add_operation(Operation::new("TL",
vec![lopdf::Object::Real(height)]
));
}
/// Sets the character spacing inside a text block
/// Values are given in points. A value of 3 (pt) will increase
/// the spacing inside a word by 3pt.
#[inline]
pub fn set_character_spacing(&self, spacing: f64) {
self.internal_add_operation(Operation::new("Tc",
vec![lopdf::Object::Real(spacing)]
));
}
/// Sets the word spacing inside a text block.
/// Same as `set_character_spacing`, just for words.
/// __Note:__ This currently does not work for external
/// fonts. External fonts are encoded with Unicode, and
/// PDF does not recognize unicode fonts. It only
/// recognizes builtin fonts done with PDFDoc encoding.
/// However, the function itself is valid and _will work_
/// with builtin fonts.
#[inline]
pub fn set_word_spacing(&self, spacing: f64) {
self.internal_add_operation(Operation::new("Tw",
vec![lopdf::Object::Real(spacing)]
));
}
/// Sets the horizontal scaling (like a "condensed" font)
/// Default value is 100 (regular scaling). Setting it to
/// 50 will reduce the width of the written text by half,
/// but stretch the text
#[inline]
pub fn set_text_scaling(&self, scaling: f64) {
self.internal_add_operation(Operation::new("Tz",
vec![lopdf::Object::Real(scaling)]
));
}
/// Offsets the current text positon (used for superscript
/// and subscript). To reset the superscript / subscript, call this
/// function with 0 as the offset. For superscript, use a positive
/// number, for subscript, use a negative number. This does not
/// change the size of the font
#[inline]
pub fn set_line_offset(&self, offset: f64) {
self.internal_add_operation(Operation::new("Ts",
vec![lopdf::Object::Real(offset)]
));
}
#[inline]
pub fn set_text_rendering_mode(&self, mode: TextRenderingMode) {
self.internal_add_operation(Operation::new("Tr",
vec![lopdf::Object::Integer(mode.into())]
));
}
/// Add text to the file at the current position by specifying font codepoints for an
/// ExternalFont
pub fn write_codepoints<I>(&self, codepoints: I)
where I: IntoIterator<Item = u16>
{
use lopdf::Object::*;
use lopdf::StringFormat::Hexadecimal;
let bytes = codepoints
.into_iter()
.flat_map(|x| {
let [b0, b1] = x.to_be_bytes();
std::iter::once(b0).chain(std::iter::once(b1))
})
.collect::<Vec<u8>>();
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
doc.pages[self.page.0]
.layers[self.layer.0]
.operations.push(Operation::new("Tj",
vec![String(bytes, Hexadecimal)]
));
}
/// Add text to the file at the current position by specifying
/// font codepoints with additional kerning offset
pub fn write_positioned_codepoints<I>(&self, codepoints: I)
where I: IntoIterator<Item = (i64, u16)>
{
use lopdf::Object::*;
use lopdf::StringFormat::Hexadecimal;
let mut list = Vec::new();
for (pos, codepoint) in codepoints {
if pos != 0 {
list.push(Integer(pos));
}
let bytes = codepoint.to_be_bytes().to_vec();
list.push(String(bytes, Hexadecimal));
}
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
doc.pages[self.page.0]
.layers[self.layer.0]
.operations.push(Operation::new("TJ", vec![Array(list)]));
}
/// Add text to the file at the current position
///
/// If the given font is a built-in font and the given text contains characters that are not
/// supported by the [Windows-1252][] encoding, these characters will be ignored.
///
/// [Windows-1252]: https://en.wikipedia.org/wiki/Windows-1252
#[inline]
pub fn write_text<S>(&self, text: S, font: &IndirectFontRef)
-> () where S: Into<String>
{
// NOTE: The unwrap() calls in this function are safe, since
// we've already checked the font for validity when it was added to the document
use lopdf::Object::*;
use lopdf::StringFormat::Hexadecimal;
let text = text.into();
// we need to transform the characters into glyph ids and then add them to the layer
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
// glyph IDs that make up this string
// kerning for each glyph id. If no kerning is present, will be 0
// must be the same length as list_gid
// let mut kerning_data = Vec::<freetype::Vector>::new();
let bytes: Vec<u8> = {
if let Font::ExternalFont(face_direct_ref) = doc.fonts.get_font(font).unwrap().data {
let mut list_gid = Vec::<u16>::new();
let font = &face_direct_ref.font_data;
for ch in text.chars() {
if let Some(glyph_id) = font.glyph_id(ch) {
list_gid.push(glyph_id);
}
}
list_gid.iter()
.flat_map(|x| vec!((x >> 8) as u8, (x & 255) as u8))
.collect::<Vec<u8>>()
} else {
// For built-in fonts, we selected the WinAnsiEncoding, see the Into<LoDictionary>
// implementation for BuiltinFont.
lopdf::Document::encode_text(Some("WinAnsiEncoding"), &text)
}
};
doc.pages[self.page.0]
.layers[self.layer.0]
.operations.push(Operation::new("Tj",
vec![String(bytes, Hexadecimal)]
));
}
/// Saves the current graphic state
#[inline]
pub fn save_graphics_state(&self) {
self.internal_add_operation(Operation::new("q", Vec::new()));
}
/// Restores the previous graphic state
#[inline]
pub fn restore_graphics_state(&self) {
self.internal_add_operation(Operation::new("Q", Vec::new()));
}
/// Add text to the file, x and y are measure in millimeter from the bottom left corner
///
/// If the given font is a built-in font and the given text contains characters that are not
/// supported by the [Windows-1252][] encoding, these characters will be ignored.
///
/// [Windows-1252]: https://en.wikipedia.org/wiki/Windows-1252
#[inline]
pub fn use_text<S>(&self, text: S, font_size: f64,
x: Mm, y: Mm, font: &IndirectFontRef)
-> () where S: Into<String>
{
self.begin_text_section();
self.set_font(font, font_size);
self.set_text_cursor(x, y);
self.write_text(text, font);
self.end_text_section();
}
/*
/// Instantiate SVG data
#[inline]
pub fn use_svg(&self, width_mm: f64, height_mm: f64,
x_mm: f64, y_mm: f64, svg_data_index: SvgIndex)
{
let svg_element_ref = {
let doc = self.document.upgrade().unwrap();
let doc = doc.borrow_mut();
let element = doc.contents.get((svg_data_index.0).0).expect("invalid svg reference");
(*element).clone()
};
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
// todo: what about width / height?
doc.pages.get_mut(self.page.0).unwrap()
.layers.get_mut(self.layer.0).unwrap()
.layer.push(PdfResource::ReferencedResource(svg_data_index.0.clone()));
}
*/
// internal function to invoke an xobject
fn internal_invoke_xobject(&self, name: String)
{
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page_mut = &mut doc.pages[self.page.0];
page_mut.layers[self.layer.0]
.operations.push(lopdf::content::Operation::new(
"Do", vec![lopdf::Object::Name(name.as_bytes().to_vec())]
));
}
// internal function to add an operation (prevents locking)
fn internal_add_operation<T>(&self, op: T)
-> () where T: Into<Operation>
{
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let layer = &mut doc.pages[self.page.0].layers[self.layer.0];
layer.operations.push(op.into());
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Wapper type for shared metadata between XMP Metadata and the `DocumentInfo` dictionary
use lopdf;
use crate::OffsetDateTime;
use {
IccProfileType, PdfConformance, XmpMetadata, DocumentInfo, IccProfile
};
use glob_defines::ICC_PROFILE_ECI_V2;
/// This is a wrapper in order to keep shared data between the documents XMP metadata and
/// the "Info" dictionary in sync
#[derive(Debug, Clone)]
pub struct PdfMetadata {
/// Creation date of the document
pub creation_date: OffsetDateTime,
/// Modification date of the document
pub modification_date: OffsetDateTime,
/// Creation date of the metadata
pub metadata_date: OffsetDateTime,
/// PDF document title
pub document_title: String,
/// Is the document trapped?
pub trapping: bool,
/// PDF document version
pub document_version: u32,
/// PDF Standard
pub conformance: PdfConformance,
/// XMP Metadata. Is ignored on save if the PDF conformance does not allow XMP
pub xmp_metadata: XmpMetadata,
/// PDF Info dictionary. Contains metadata for this document
pub document_info: DocumentInfo,
/// Target color profile
pub target_icc_profile: Option<IccProfile>,
}
impl PdfMetadata {
/// Creates a new metadat object
pub fn new<S>(title: S, document_version: u32, trapping: bool, conformance: PdfConformance)
-> Self where S: Into<String>
{
let current_time = OffsetDateTime::now_utc();
Self {
creation_date: current_time.clone(),
modification_date: current_time.clone(),
metadata_date: current_time.clone(),
document_title: title.into(),
trapping: trapping,
document_version: document_version,
conformance: conformance,
xmp_metadata: XmpMetadata::new(Some("default".into()), 1),
document_info: DocumentInfo::new(),
target_icc_profile: None,
}
}
/// Consumes the metadata, returning the (Option<xmp_metadata>, document_info, icc_profile_stream).
pub fn into_obj(self)
-> (Option<lopdf::Object>, lopdf::Object, Option<IccProfile>)
{
let xmp_obj = {
if self.conformance.must_have_xmp_metadata() {
Some(self.xmp_metadata.into_obj(
self.conformance.clone(),
self.trapping,
self.creation_date.clone(),
self.modification_date.clone(),
self.metadata_date,
self.document_title.clone()))
} else {
None
}
};
let doc_info_obj = self.document_info.into_obj(self.document_title,
self.trapping,
self.conformance.clone(),
self.creation_date.clone(),
self.modification_date.clone());
// add icc profile if necessary
let icc_profile = {
if self.conformance.must_have_icc_profile() {
match self.target_icc_profile {
Some(icc) => Some(icc),
None => Some(IccProfile::new(ICC_PROFILE_ECI_V2.to_vec(), IccProfileType::Cmyk)
.with_alternate_profile(false)
.with_range(true)),
}
} else {
None
}
};
(xmp_obj, doc_info_obj, icc_profile)
}
}
+186
View File
@@ -0,0 +1,186 @@
//! PDF page management
use lopdf;
use std::rc::Weak;
use std::cell::RefCell;
use indices::{PdfPageIndex, PdfLayerIndex};
use {
PdfResources, PdfLayer, PdfDocument, ExtendedGraphicsState, ExtendedGraphicsStateRef, Pattern, XObject, XObjectRef,
PdfLayerReference, PatternRef, Mm, Pt
};
/// PDF page
#[derive(Debug, Clone)]
pub struct PdfPage {
/// The index of the page in the document
pub(crate) index: usize,
/// page width in point
pub width: Pt,
/// page height in point
pub height: Pt,
/// Page layers
pub layers: Vec<PdfLayer>,
/// Resources used in this page
pub(crate) resources: PdfResources,
}
/// A "reference" to the current page, allows for inner mutability
/// but only inside this library
pub struct PdfPageReference {
/// A weak reference to the document, for inner mutability
pub document: Weak<RefCell<PdfDocument>>,
/// The index of the page this layer is on
pub page: PdfPageIndex,
}
impl PdfPage {
/// Create a new page, notice that width / height are in millimeter.
/// Page must contain at least one layer
#[inline]
pub fn new<S>(width: Mm,
height: Mm,
layer_name: S,
page_index: usize)
-> (Self, PdfLayerIndex) where S: Into<String>
{
let mut page = Self {
index: page_index,
width: width.into(),
height: height.into(),
layers: Vec::new(),
resources: PdfResources::new(),
};
let initial_layer = PdfLayer::new(layer_name);
page.layers.push(initial_layer);
let layer_index = page.layers.len() - 1;
(page, PdfLayerIndex(layer_index))
}
/// Iterates through the layers attached to this page and gathers all resources,
/// which the layers need. Then returns a dictonary with all the resources
/// (fonts, image XObjects, etc.)
///
/// While originally I had planned to build a system where you can reference contents
/// from all over the document, this turned out to be a problem, because each type had
/// to be handled differently (PDF weirdness)
///
/// `layers` should be a Vec with all layers (optional content groups) that were added
/// to the document on a document level, it should contain the indices of the layers
/// (they will be ignored, todo) and references to the actual OCG dictionaries
#[inline]
pub(crate) fn collect_resources_and_streams(self, doc: &mut lopdf::Document, layers: &[(usize, lopdf::Object)])
-> (lopdf::Dictionary, Vec<lopdf::Stream>)
{
let cur_layers = layers.iter().map(|l| l.1.clone()).collect();
let (resource_dictionary, ocg_refs) = self.resources.into_with_document_and_layers(doc, cur_layers);
// set contents
let mut layer_streams = Vec::<lopdf::Stream>::new();
use lopdf::content::Operation;
use lopdf::Object::*;
for (idx, mut layer) in self.layers.into_iter().enumerate() {
// push OCG and q to the beginning of the layer
layer.operations.insert(0, Operation::new("q".into(), vec![]));
layer.operations.insert(0, Operation::new("BDC".into(), vec![
Name("OC".into()),
Name(ocg_refs[idx].name.clone().into())
]));
// push OCG END and Q to the end of the layer stream
layer.operations.push(Operation::new("Q".into(), vec![]));
layer.operations.push(Operation::new("EMC".into(), vec![]));
// should end up looking like this:
// /OC /MC0 BDC
// q
// <layer stream content>
// Q
// EMC
let layer_stream = layer.into();
layer_streams.push(layer_stream);
}
(resource_dictionary, layer_streams)
}
/// Change the graphics state. Before this operation is done, you should save
/// the graphics state using the `save_graphics_state()` function. This will change the
/// current graphics state until the end of the page or until the page is reset to the
/// previous state.
/// Returns the old graphics state, in case it was overwritten, as well as a reference
/// to the currently active graphics state
#[inline]
pub fn add_graphics_state(&mut self, added_state: ExtendedGraphicsState)
-> ExtendedGraphicsStateRef
{
self.resources.add_graphics_state(added_state)
}
/// __STUB__: Adds a pattern to the pages resources
#[inline]
pub fn add_pattern(&mut self, pattern: Pattern)
-> PatternRef
{
self.resources.add_pattern(pattern)
}
/// __STUB__: Adds an XObject to the pages resources.
/// __NOTE__: Watch out for scaling. Your XObject might be invisible or only 1pt x 1pt big
#[inline]
pub fn add_xobject(&mut self, xobj: XObject)
-> XObjectRef
{
self.resources.add_xobject(xobj)
}
}
impl PdfPageReference {
/// Adds a page and returns the index of the currently added page
#[inline]
pub fn add_layer<S>(&self, layer_name: S)
-> PdfLayerReference where S: Into<String>
{
let doc = self.document.upgrade().unwrap();
let mut doc = doc.borrow_mut();
let page = &mut doc.pages[self.page.0];
let current_page_index = page.layers.len(); /* order is important */
let layer = PdfLayer::new(layer_name);
page.layers.push(layer);
let index = PdfLayerIndex(current_page_index);
PdfLayerReference {
document: self.document.clone(),
page: self.page,
layer: index,
}
}
/// Validates that a layer is present and returns a reference to it
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(no_effect))]
pub fn get_layer(&self, layer: PdfLayerIndex)
-> PdfLayerReference
{
let doc = self.document.upgrade().unwrap();
let doc = doc.borrow();
let _ = &doc.pages[self.page.0].layers[layer.0];
PdfLayerReference {
document: self.document.clone(),
page: self.page,
layer: layer,
}
}
}
+244
View File
@@ -0,0 +1,244 @@
//! Color module (CMYK or RGB). Shared between 2D and 3D module.
#[cfg(feature = "embedded_images")]
use image;
use lopdf::content::Operation;
use glob_defines::{
OP_COLOR_SET_FILL_CS_DEVICERGB, OP_COLOR_SET_FILL_CS_DEVICECMYK, OP_COLOR_SET_FILL_CS_DEVICEGRAY,
OP_COLOR_SET_STROKE_CS_DEVICERGB, OP_COLOR_SET_STROKE_CS_DEVICECMYK, OP_COLOR_SET_STROKE_CS_DEVICEGRAY,
};
use IccProfileRef;
/// Tuple for differentiating outline and fill colors
#[derive(Debug, Clone, PartialEq)]
pub enum PdfColor {
FillColor(Color),
OutlineColor(Color),
}
impl Into<Operation> for PdfColor {
fn into(self)
-> Operation
{
use lopdf::Object::*;
// todo: incorporate ICC profile instead of just setting the default device cmyk color space
let (color_identifier, color_vec) = {
use self::PdfColor::*;
match self {
FillColor(fill) => {
let ci = match fill {
Color::Rgb(_) => { OP_COLOR_SET_FILL_CS_DEVICERGB }
Color::Cmyk(_) | Color::SpotColor(_) => { OP_COLOR_SET_FILL_CS_DEVICECMYK }
Color::Greyscale(_) => { OP_COLOR_SET_FILL_CS_DEVICEGRAY }
};
let cvec = fill.into_vec().into_iter().map(Real).collect();
(ci, cvec)
},
OutlineColor(outline) => {
let ci = match outline {
Color::Rgb(_) => { OP_COLOR_SET_STROKE_CS_DEVICERGB }
Color::Cmyk(_) | Color::SpotColor(_) => { OP_COLOR_SET_STROKE_CS_DEVICECMYK }
Color::Greyscale(_) => { OP_COLOR_SET_STROKE_CS_DEVICEGRAY }
};
let cvec = outline.into_vec().into_iter().map(Real).collect();
(ci, cvec)
}
}
};
Operation::new(color_identifier, color_vec)
}
}
/// Color space (enum for marking the number of bits a color has)
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
Rgb,
Rgba,
Palette,
Cmyk,
Greyscale,
GreyscaleAlpha,
}
#[cfg(feature = "embedded_images")]
impl From<image::ColorType> for ColorSpace {
fn from(color_type: image::ColorType)
-> Self
{
use image::ColorType::*;
match color_type {
L8 | L16 => ColorSpace::Greyscale,
La8 | La16 => ColorSpace::GreyscaleAlpha,
Rgb8 | Bgr8 | Rgb16 => ColorSpace::Rgb,
Rgba8 | Bgra8 | Rgba16 => ColorSpace::Rgba,
_ => ColorSpace::Greyscale, // unreachable
}
}
}
impl Into<&'static str> for ColorSpace {
fn into(self)
-> &'static str
{
use self::ColorSpace::*;
match self {
Rgb => "DeviceRGB",
Cmyk => "DeviceCMYK",
Greyscale => "DeviceGray",
Palette => "Indexed",
Rgba | GreyscaleAlpha => "DeviceN",
}
}
}
/// How many bits does a color have?
#[derive(Debug, Copy, Clone)]
pub enum ColorBits {
Bit1,
Bit8,
Bit16,
}
#[cfg(feature = "embedded_images")]
impl From<image::ColorType> for ColorBits {
fn from(color_type: image::ColorType)
-> ColorBits
{
use image::ColorType::*;
use ColorBits::*;
match color_type {
L8 | La8 | Rgb8 | Rgba8 | Bgr8 | Bgra8 => Bit8,
L16 | La16 | Rgb16 | Rgba16 => Bit16,
_ => Bit8, // unreachable
}
}
}
impl Into<i64> for ColorBits {
fn into(self)
-> i64
{
match self {
ColorBits::Bit1 => 1,
ColorBits::Bit8 => 8,
ColorBits::Bit16 => 16,
}
}
}
/// Wrapper for Rgb, Cmyk and other color types
#[derive(Debug, Clone, PartialEq)]
pub enum Color {
Rgb(Rgb),
Cmyk(Cmyk),
Greyscale(Greyscale),
SpotColor(SpotColor)
}
impl Color {
/// Consumes the color and converts into into a vector of numbers
pub fn into_vec(self)
-> Vec<f64>
{
match self {
Color::Rgb(rgb) => { vec![rgb.r, rgb.g, rgb.b ]},
Color::Cmyk(cmyk) => { vec![cmyk.c, cmyk.m, cmyk.y, cmyk.k ]},
Color::Greyscale(gs) => { vec![gs.percent]},
Color::SpotColor(spot) => { vec![spot.c, spot.m, spot.y, spot.k ]},
}
}
/// Returns if the color has an icc profile attached
pub fn get_icc_profile(&self)
-> Option<&Option<IccProfileRef>>
{
match *self {
Color::Rgb(ref rgb) => Some(&rgb.icc_profile),
Color::Cmyk(ref cmyk) => Some(&cmyk.icc_profile),
Color::Greyscale(ref gs) => Some(&gs.icc_profile),
Color::SpotColor(_) => None,
}
}
}
/// RGB color
#[derive(Debug, Clone, PartialEq)]
pub struct Rgb {
pub r: f64,
pub g: f64,
pub b: f64,
pub icc_profile: Option<IccProfileRef>,
}
impl Rgb {
pub fn new(r: f64, g: f64, b: f64, icc_profile: Option<IccProfileRef>)
-> Self
{
Self { r, g, b, icc_profile }
}
}
/// CMYK color
#[derive(Debug, Clone, PartialEq)]
pub struct Cmyk {
pub c: f64,
pub m: f64,
pub y: f64,
pub k: f64,
pub icc_profile: Option<IccProfileRef>,
}
impl Cmyk {
/// Creates a new CMYK color
pub fn new(c: f64, m: f64, y: f64, k: f64, icc_profile: Option<IccProfileRef>)
-> Self
{
Self { c, m, y, k, icc_profile }
}
}
/// Greyscale color
#[derive(Debug, Clone, PartialEq)]
pub struct Greyscale {
pub percent: f64,
pub icc_profile: Option<IccProfileRef>,
}
impl Greyscale {
pub fn new(percent: f64, icc_profile: Option<IccProfileRef>)
-> Self
{
Self { percent, icc_profile }
}
}
/// Spot color
/// Spot colors are like Cmyk, but without color space
/// They are essentially "named" colors from specific vendors
/// currently they are the same as a CMYK color.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct SpotColor {
pub c: f64,
pub m: f64,
pub y: f64,
pub k: f64,
}
impl SpotColor {
pub fn new(c: f64, m: f64, y: f64, k: f64)
-> Self
{
Self { c, m, y, k }
}
}
+133
View File
@@ -0,0 +1,133 @@
//! Current transformation matrix, for transforming shapes (rotate, translate, scale)
use lopdf;
use lopdf::content::Operation;
use {Mm, Pt};
/// PDF "current transformation matrix". Once set, will operate on all following shapes,
/// until the `layer.restore_graphics_state()` is called. It is important to
/// call `layer.save_graphics_state()` earlier.
#[derive(Debug, Copy, Clone)]
pub enum CurTransMat {
/// Translation matrix (in points from bottom left corner)
/// X and Y can have different values
Translate(Mm, Mm),
/// Rotation matrix (clockwise, in degrees)
Rotate(f64),
/// Scale matrix (1.0 = 100% scale, no change)
/// X and Y can have different values
Scale(f64, f64),
/// Identity matrix
Identity,
}
/// Text matrix. Text placement is a bit different, but uses the same
/// concepts as a CTM that's why it's merged here
///
/// Note: `TextScale` does not exist. Use `layer.set_word_spacing()`
/// and `layer.set_character_spacing()` to specify the scaling between words
/// and characters.
#[derive(Debug, Copy, Clone)]
pub enum TextMatrix {
/// Text rotation matrix, used for rotating text
Rotate(f64),
/// Text translate matrix, used for indenting (transforming) text
/// (different to regular text placement)
Translate(Mm, Mm),
}
impl Into<[f64; 6]> for TextMatrix {
fn into(self)
-> [f64; 6]
{
use TextMatrix::*;
match self {
Translate(x, y) => {
// 1 0 0 1 x y cm
let x_pt: Pt = x.into();
let y_pt: Pt = y.into();
[ 1.0, 0.0, 0.0, 1.0, x_pt.0, y_pt.0 ]
}
Rotate(rot) => { let rad = (360.0 - rot).to_radians(); [rad.cos(), -rad.sin(), rad.sin(), rad.cos(), 0.0, 0.0 ] /* cos sin -sin cos 0 0 cm */ }
}
}
}
impl Into<[f64; 6]> for CurTransMat {
fn into(self)
-> [f64; 6]
{
use CurTransMat::*;
match self {
Translate(x, y) => {
// 1 0 0 1 x y cm
let x_pt: Pt = x.into();
let y_pt: Pt = y.into();
[ 1.0, 0.0, 0.0, 1.0, x_pt.0, y_pt.0 ]
}
Rotate(rot) => {
// cos sin -sin cos 0 0 cm
let rad = (360.0 - rot).to_radians();
[rad.cos(), -rad.sin(), rad.sin(), rad.cos(), 0.0, 0.0 ]
}
Scale(x, y) => {
// x 0 0 y 0 0 cm
[ x, 0.0, 0.0, y, 0.0, 0.0 ]
}
Identity => {
[ 1.0, 0.0, 0.0, 1.0, 0.0, 0.0 ]
}
}
}
}
impl Into<Operation> for CurTransMat {
fn into(self)
-> Operation
{
use lopdf::Object::*;
let matrix_nums: [f64; 6] = self.into();
let matrix: Vec<lopdf::Object> = matrix_nums.to_vec().into_iter().map(Real).collect();
Operation::new("cm", matrix)
}
}
impl Into<Operation> for TextMatrix {
fn into(self)
-> Operation
{
use lopdf::Object::*;
let matrix_nums: [f64; 6] = self.into();
let matrix: Vec<lopdf::Object> = matrix_nums.to_vec().into_iter().map(Real).collect();
Operation::new("Tm", matrix)
}
}
impl Into<lopdf::Object> for CurTransMat {
fn into(self)
-> lopdf::Object
{
use lopdf::Object::*;
let matrix_nums: [f64; 6] = self.into();
Array(matrix_nums.to_vec().into_iter().map(Real).collect())
}
}
#[test]
fn test_ctm_translate()
{
use self::*;
// test that the translation matrix look like what PDF expects
let ctm_trans = CurTransMat::Translate(Mm(150.0), Mm(50.0));
let ctm_trans_arr: [f64; 6] = ctm_trans.into();
assert_eq!([1.0_f64, 0.0, 0.0, 1.0, 425.1969, 141.7323], ctm_trans_arr);
let ctm_scale = CurTransMat::Scale(2.0, 4.0);
let ctm_scale_arr: [f64; 6] = ctm_scale.into();
assert_eq!([2.0_f64, 0.0, 0.0, 4.0, 0.0, 0.0], ctm_scale_arr);
let ctm_rot = CurTransMat::Rotate(30.0);
let ctm_rot_arr: [f64; 6] = ctm_rot.into();
assert_eq!([0.8660254037844384, 0.5000000000000004, -0.5000000000000004, 0.8660254037844384, 0.0, 0.0], ctm_rot_arr);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,137 @@
//! ICC profile that can be embedded into a PDF
extern crate lopdf;
/// Type of the icc profile
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum IccProfileType {
Cmyk,
Rgb,
Greyscale,
}
/// Icc profile
#[derive(Debug, Clone, PartialEq)]
pub struct IccProfile {
/// Binary Icc profile
icc: Vec<u8>,
/// CMYK or RGB or LAB icc profile?
icc_type: IccProfileType,
/// Does the ICC profile have an "Alternate" version or not?
pub has_alternate: bool,
/// Does the ICC profile have an "Range" dictionary
/// Really not sure why this is needed, but this is needed on the documents Info dictionary
pub has_range: bool,
}
impl IccProfile {
/// Creates a new Icc Profile
pub fn new(icc: Vec<u8>, icc_type: IccProfileType)
-> Self
{
Self {
icc: icc,
icc_type: icc_type,
has_alternate: true,
has_range: false,
}
}
/// Does the ICC profile have an alternate version (such as "DeviceCMYk")?
#[inline]
pub fn with_alternate_profile(mut self, has_alternate: bool)
-> Self
{
self.has_alternate = has_alternate;
self
}
/// Does the ICC profile have an "Range" dictionary?
#[inline]
pub fn with_range(mut self, has_range: bool)
-> Self
{
self.has_range = has_range;
self
}
}
impl Into<lopdf::Stream> for IccProfile {
fn into(self)
-> lopdf::Stream
{
use lopdf::{Dictionary as LoDictionary,
Stream as LoStream};
use lopdf::Object::*;
use std::iter::FromIterator;
let (num_icc_fields, alternate) = match self.icc_type {
IccProfileType::Cmyk => (4, "DeviceCMYK"),
IccProfileType::Rgb => (3, "DeviceRGB"),
IccProfileType::Greyscale => (1, "DeviceGray"),
};
let mut stream_dict = LoDictionary::from_iter(vec![
("N", Integer(num_icc_fields)).into(),
("Length", Integer(self.icc.len() as i64).into())]);
if self.has_alternate {
stream_dict.set("Alternate", Name(alternate.into()));
}
if self.has_range {
stream_dict.set("Range", Array(vec![
Real(0.0),
Real(1.0),
Real(0.0),
Real(1.0),
Real(0.0),
Real(1.0),
Real(0.0),
Real(1.0)]));
}
LoStream::new(stream_dict, self.icc)
}
}
/// Named reference for an ICC profile
#[derive(Debug, Clone, PartialEq)]
pub struct IccProfileRef {
pub(crate) name: String,
}
impl IccProfileRef {
/// Creates a new IccProfileRef
pub fn new(index: usize)
-> Self
{
Self {
name: format!("/ICC{}", index)
}
}
}
#[derive(Default, Clone, Debug, PartialEq)]
pub struct IccProfileList {
profiles: Vec<IccProfile>,
}
impl IccProfileList {
/// Creates a new IccProfileList
pub fn new()
-> Self
{
Self::default()
}
/// Adds an ICC profile
pub fn add_profile(&mut self, profile: IccProfile)
-> IccProfileRef
{
let cur_len = self.profiles.len();
self.profiles.push(profile);
IccProfileRef::new(cur_len)
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Module for graphics (line, polygon, 3D, etc.)
pub mod two_dimensional;
pub mod three_dimensional;
pub use self::two_dimensional::*;
pub use self::three_dimensional::*;
pub mod color;
pub mod ocg;
pub mod icc_profile;
pub mod ctm;
pub mod extgstate;
pub mod xobject;
pub mod pattern;
pub mod pdf_resources;
pub use self::ctm::*;
pub use self::ocg::*;
pub use self::color::*;
pub use self::icc_profile::*;
pub use self::extgstate::*;
pub use self::xobject::*;
pub use self::pattern::*;
pub use self::pdf_resources::*;
+59
View File
@@ -0,0 +1,59 @@
extern crate lopdf;
#[derive(Default, Debug, Clone)]
pub struct OCGList {
/// The reference to the layer as well as a reference to the
/// OCG dictionary
pub(crate) layers: Vec<(OCGRef, lopdf::Object)>,
}
impl OCGList {
/// Creates a new OCG list
pub fn new()
-> Self
{
Self::default()
}
/// Adds a new OCG List from a reference
pub fn add_ocg(&mut self, obj: lopdf::Object)
-> OCGRef
{
let len = self.layers.len();
let ocg_ref = OCGRef::new(len);
self.layers.push((ocg_ref.clone(), obj));
ocg_ref
}
}
impl Into<lopdf::Dictionary> for OCGList {
#[cfg_attr(feature = "cargo-clippy", allow(needless_return))]
fn into(self)
-> lopdf::Dictionary
{
let mut dict = lopdf::Dictionary::new();
for entry in self.layers {
dict.set(entry.0.name, entry.1);
}
return dict;
}
}
#[derive(Debug, Clone)]
pub struct OCGRef {
/// The referenced name of the layer
pub(crate) name: String,
}
impl OCGRef {
/// Creates a new OCG reference from an index
pub fn new(index: usize)
-> Self
{
Self {
name: format!("MC{}", index),
}
}
}
+68
View File
@@ -0,0 +1,68 @@
use lopdf;
use std::collections::HashMap;
/// __STUB__
#[derive(Default, Debug, Copy, Clone)]
pub struct Pattern {
}
impl Pattern {
/// Creates a new Pattern
pub fn new()
-> Self
{
Self::default()
}
}
/// Named reference to a pattern
#[derive(Debug)]
pub struct PatternRef {
pub(crate) name: String,
}
impl PatternRef {
pub fn new(index: usize)
-> Self
{
Self {
name: format!("PT{}", index),
}
}
}
#[derive(Default, Debug, Clone)]
pub struct PatternList {
patterns: HashMap<String, Pattern>,
}
impl PatternList {
/// Creates a new pattern list
pub fn new()
-> Self
{
Self {
patterns: HashMap::new(),
}
}
/// Adds a new pattern to the pattern list
pub fn add_pattern(&mut self, pattern: Pattern)
-> PatternRef
{
let len = self.patterns.len();
let pattern_ref = PatternRef::new(len);
self.patterns.insert(pattern_ref.name.clone(), pattern);
pattern_ref
}
}
impl Into<lopdf::Dictionary> for PatternList {
fn into(self)
-> lopdf::Dictionary
{
// todo
lopdf::Dictionary::new()
}
}
@@ -0,0 +1,97 @@
use lopdf;
use {
XObject, Pattern, ExtendedGraphicsState, ExtendedGraphicsStateList,
PatternRef, OCGRef, XObjectList, XObjectRef, ExtendedGraphicsStateRef,
OCGList, PatternList
};
/// Struct for storing the PDF Resources, to be used on a PDF page
#[derive(Default, Debug, Clone)]
pub struct PdfResources {
/// External graphics objects
pub xobjects: XObjectList,
/// Patterns used on this page. Do not yet, use, placeholder.
pub patterns: PatternList,
/// Graphics states used on this page
pub graphics_states: ExtendedGraphicsStateList,
/// Layers / optional content ("Properties") in the resource dictionary
pub layers: OCGList,
}
impl PdfResources {
/// Creates a new PdfResources struct (resources for exactly one PDF page)
pub fn new()
-> Self
{
Self::default()
}
/// Add a graphics state to the resources
#[inline]
pub fn add_graphics_state(&mut self, added_state: ExtendedGraphicsState)
-> ExtendedGraphicsStateRef
{
self.graphics_states.add_graphics_state(added_state)
}
/// Adds an XObject to the page
#[inline]
pub fn add_xobject(&mut self, xobj: XObject)
-> XObjectRef
{
self.xobjects.add_xobject(xobj)
}
/// __STUB__: Adds a pattern to the resources, to be used like a color
#[inline]
pub fn add_pattern(&mut self, pattern: Pattern)
-> PatternRef
{
self.patterns.add_pattern(pattern)
}
/// See `XObject::Into_with_document`.
/// The resources also need access to the layers (the optional content groups), this should be a
/// `Vec<lopdf::Object::Reference>` (to the actual OCG groups, which are added on the document level)
#[cfg_attr(feature = "cargo-clippy", allow(needless_return))]
pub fn into_with_document_and_layers(self, doc: &mut lopdf::Document, layers: Vec<lopdf::Object>)
-> (lopdf::Dictionary, Vec<OCGRef>)
{
let mut dict = lopdf::Dictionary::new();
let mut ocg_dict = self.layers;
let mut ocg_references = Vec::<OCGRef>::new();
let xobjects_dict: lopdf::Dictionary = self.xobjects.into_with_document(doc);
let patterns_dict: lopdf::Dictionary = self.patterns.into();
let graphics_state_dict: lopdf::Dictionary = self.graphics_states.into();
if !layers.is_empty() {
for l in layers {
ocg_references.push(ocg_dict.add_ocg(l));
}
let cur_ocg_dict_obj: lopdf::Dictionary = ocg_dict.into();
if cur_ocg_dict_obj.len() > 0 {
dict.set("Properties", lopdf::Object::Dictionary(cur_ocg_dict_obj));
}
}
if xobjects_dict.len() > 0 {
dict.set("XObject", lopdf::Object::Dictionary(xobjects_dict));
}
if patterns_dict.len() > 0 {
dict.set("Pattern", lopdf::Object::Dictionary(patterns_dict));
}
if graphics_state_dict.len() > 0 {
dict.set("ExtGState", lopdf::Object::Dictionary(graphics_state_dict));
}
return (dict, ocg_references);
}
}
@@ -0,0 +1 @@
//! 3D Graphics for Pdf (stub)
@@ -0,0 +1,571 @@
#![allow(trivial_numeric_casts)]
//! Embedding fonts in 2D for Pdf
use lopdf;
use lopdf::{Stream as LoStream, Dictionary as LoDictionary};
use lopdf::StringFormat;
use std::collections::BTreeMap;
use std::iter::FromIterator;
use Error;
use rusttype::FontCollection;
/// The font
#[derive(Debug, Clone, PartialEq)]
pub enum Font {
/// Represents one of the 14 built-in fonts (Arial, Helvetica, etc.)
BuiltinFont(BuiltinFont),
/// Represents a font loaded from an external file
ExternalFont(ExternalFont),
}
/// Standard built-in PDF fonts
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum BuiltinFont {
TimesRoman,
TimesBold,
TimesItalic,
TimesBoldItalic,
Helvetica,
HelveticaBold,
HelveticaOblique,
HelveticaBoldOblique,
Courier,
CourierOblique,
CourierBold,
CourierBoldOblique,
Symbol,
ZapfDingbats,
}
impl Into<&'static str> for BuiltinFont {
fn into(self) -> &'static str {
use BuiltinFont::*;
match self {
TimesRoman => "Times-Roman",
TimesBold => "Times-Bold",
TimesItalic => "Times-Italic",
TimesBoldItalic => "Times-BoldItalic",
Helvetica => "Helvetica",
HelveticaBold => "Helvetica-Bold",
HelveticaOblique => "Helvetica-Oblique",
HelveticaBoldOblique => "Helvetica-BoldOblique",
Courier => "Courier",
CourierOblique => "Courier-Oblique",
CourierBold => "Courier-Bold",
CourierBoldOblique => "Courier-BoldOblique",
Symbol => "Symbol",
ZapfDingbats => "ZapfDingbats",
}
}
}
impl Into<LoDictionary> for BuiltinFont {
fn into(self) -> LoDictionary {
use lopdf::Object;
use lopdf::Object::*;
let font_id: &'static str = self.into();
// Begin setting required font attributes
let font_vec: Vec<(::std::string::String, Object)> = vec![
("Type".into(), Name("Font".into())),
("Subtype".into(), Name("Type1".into())),
("BaseFont".into(), Name(font_id.into())),
("Encoding".into(), Name("WinAnsiEncoding".into())),
// Missing DescendantFonts and ToUnicode
];
LoDictionary::from_iter(font_vec)
}
}
#[derive(Debug, Clone)]
pub struct ExternalFont {
/// Raw font data
pub(crate) font_bytes: Vec<u8>,
/// Parsed font data
pub(crate) font_data: Box<dyn FontData>,
/// Font name, for adding as a resource on the document
pub(crate) face_name: String,
/// Is the font written vertically? Default: false
pub(crate) vertical_writing: bool,
}
/// The text rendering mode determines how a text is drawn
/// The default rendering mode is `Fill`. The color of the
/// fill / stroke is determine by the current pages outline /
/// fill color.
///
/// See PDF Reference 1.7 Page 402
#[derive(Debug, Copy, Clone)]
pub enum TextRenderingMode {
Fill,
Stroke,
FillStroke,
Invisible,
FillClip,
StrokeClip,
FillStrokeClip,
Clip,
}
impl Into<i64> for TextRenderingMode {
fn into(self)
-> i64
{
use TextRenderingMode::*;
match self {
Fill => 0,
Stroke => 1,
FillStroke => 2,
Invisible => 3,
FillClip => 4,
StrokeClip => 5,
FillStrokeClip => 6,
Clip => 7,
}
}
}
impl ExternalFont {
/// Creates a new font. The `index` is used for naming / identifying the font
///
/// This method uses [`rusttype`][] to parse the font data. If you want to use a different
/// font backend, use the [`with_font_data`][] method instead.
///
/// [`rusttype`]: https://docs.rs/rusttype/latest/rusttype/
/// [`with_font_data`]: #method.with_font_data
pub fn new<R>(mut font_stream: R, font_index: usize)
-> Result<Self, Error> where R: ::std::io::Read
{
// read font from stream and parse font metrics
let mut buf = Vec::<u8>::new();
font_stream.read_to_end(&mut buf)?;
let collection = FontCollection::from_bytes(buf.clone())?;
let font = collection.clone().into_font().or_else(|_| collection.font_at(0))?;
Ok(Self::with_font_data(buf, font_index, Box::new(font)))
}
/// Creates a new font. The `index` is used for naming / identifying the font
pub fn with_font_data(bytes: Vec<u8>, font_index: usize, font_data: Box<dyn FontData>) -> Self {
let face_name = format!("F{}", font_index);
Self {
font_bytes: bytes,
font_data,
face_name,
vertical_writing: false,
}
}
/// Takes the font and adds it to the document and consumes the font
pub(crate) fn into_with_document(self, doc: &mut lopdf::Document)
-> LoDictionary
{
use lopdf::Object;
use lopdf::Object::*;
let face_name = self.face_name.clone();
// Extract basic font information
let face_metrics = self.font_data.font_metrics();
let font_stream = LoStream::new(
LoDictionary::from_iter(vec![
("Length1", Integer(self.font_bytes.len() as i64)),
]),
self.font_bytes)
.with_compression(true);
// Begin setting required font attributes
let mut font_vec: Vec<(::std::string::String, Object)> = vec![
("Type".into(), Name("Font".into())),
("Subtype".into(), Name("Type0".into())),
("BaseFont".into(), Name(face_name.clone().into_bytes())),
// Identity-H for horizontal writing, Identity-V for vertical writing
("Encoding".into(), Name("Identity-H".into())),
// Missing DescendantFonts and ToUnicode
];
let mut font_descriptor_vec: Vec<(::std::string::String, Object)> = vec![
("Type".into(), Name("FontDescriptor".into())),
("FontName".into(), Name(face_name.clone().into_bytes())),
("Ascent".into(), Integer(i64::from(face_metrics.ascent))),
("Descent".into(), Integer(i64::from(face_metrics.descent))),
("CapHeight".into(), Integer(i64::from(face_metrics.ascent))),
("ItalicAngle".into(), Integer(0)),
("Flags".into(), Integer(32)),
("StemV".into(), Integer(80)),
];
// End setting required font arguments
// Maximum height of a single character in the font
let mut max_height = 0;
// Total width of all characters
let mut total_width = 0;
// Widths (or heights, depends on self.vertical_writing)
// of the individual characters, indexed by glyph id
let mut widths = Vec::<(u32, u32)>::new();
// Glyph IDs - (Unicode IDs - character width, character height)
let mut cmap = BTreeMap::<u32, (u32, u32, u32)>::new();
cmap.insert(0, (0, 1000, 1000));
for (glyph_id, c) in self.font_data.glyph_ids() {
if let Some(glyph_metrics) = self.font_data.glyph_metrics(glyph_id) {
if glyph_metrics.height > max_height {
max_height = glyph_metrics.height;
}
total_width += glyph_metrics.width;
cmap.insert(glyph_id as u32,
(c as u32, glyph_metrics.width as u32, glyph_metrics.height as u32));
}
}
// Maps the character index to a unicode value - add this to the "ToUnicode" dictionary!
//
// To explain this structure: Glyph IDs have to be in segments where the first byte of the
// first and last element have to be the same. A range from 0x1000 - 0x10FF is valid
// but a range from 0x1000 - 0x12FF is not (0x10 != 0x12)
// Plus, the maximum number of Glyph-IDs in one range is 100
//
// Since the glyph IDs are sequential, all we really have to do is to enumerate the vector
// and create buckets of 100 / rest to 256 if needed
let mut cur_first_bit: u16 = 0_u16; // current first bit of the glyph id (0x10 or 0x12) for example
let mut all_cmap_blocks = Vec::new();
{
let mut current_cmap_block = Vec::new();
for (glyph_id, unicode_width_tuple) in &cmap {
if (*glyph_id >> 8) as u16 != cur_first_bit || current_cmap_block.len() >= 100 {
// end the current (beginbfchar endbfchar) block
all_cmap_blocks.push(current_cmap_block.clone());
current_cmap_block = Vec::new();
cur_first_bit = (*glyph_id >> 8) as u16;
}
let (unicode, width, _) = *unicode_width_tuple;
current_cmap_block.push((*glyph_id, unicode));
widths.push((*glyph_id, width));
};
all_cmap_blocks.push(current_cmap_block);
}
let cid_to_unicode_map = generate_cid_to_unicode_map(face_name.clone(), all_cmap_blocks);
let cid_to_unicode_map_stream = LoStream::new(LoDictionary::new(), cid_to_unicode_map.as_bytes().to_vec());
let cid_to_unicode_map_stream_id = doc.add_object(cid_to_unicode_map_stream);
// encode widths / heights so that they fit into what PDF expects
// see page 439 in the PDF 1.7 reference
// basically widths_list will contain objects like this:
// 20 [21, 99, 34, 25]
// which means that the character with the GID 20 has a width of 21 units
// and the character with the GID 21 has a width of 99 units
let mut widths_list = Vec::<Object>::new();
let mut current_low_gid = 0;
let mut current_high_gid = 0;
let mut current_width_vec = Vec::<Object>::new();
// scale the font width so that it sort-of fits into an 1000 unit square
let percentage_font_scaling = 1000.0 / (face_metrics.units_per_em as f64);
for (gid, width) in widths {
if gid == current_high_gid {
current_width_vec.push(Integer((width as f64 * percentage_font_scaling) as i64));
current_high_gid += 1;
} else {
widths_list.push(Integer(current_low_gid as i64));
widths_list.push(Array(current_width_vec.drain(..).collect()));
current_width_vec.push(Integer((width as f64 * percentage_font_scaling) as i64));
current_low_gid = gid;
current_high_gid = gid + 1;
}
}
// push the last widths, because the loop is delayed by one iteration
widths_list.push(Integer(current_low_gid as i64));
widths_list.push(Array(current_width_vec.drain(..).collect()));
let w = {
if self.vertical_writing { ("W2", Array(widths_list)) }
else { ("W", Array(widths_list)) }
};
// default width for characters
let dw = {
if self.vertical_writing { ("DW2", Integer(1000)) }
else { ("DW", Integer(1000)) }
};
let mut desc_fonts = LoDictionary::from_iter(vec![
("Type", Name("Font".into())),
("Subtype", Name("CIDFontType2".into())),
("BaseFont", Name(face_name.clone().into())),
("CIDSystemInfo", Dictionary(LoDictionary::from_iter(vec![
("Registry", String("Adobe".into(), StringFormat::Literal)),
("Ordering", String("Identity".into(), StringFormat::Literal)),
("Supplement", Integer(0)),
]))),
w, dw,
]);
let font_bbox = vec![ Integer(0), Integer(max_height as i64), Integer(total_width as i64), Integer(max_height as i64) ];
font_descriptor_vec.push(("FontFile2".into(), Reference(doc.add_object(font_stream))));
// although the following entry is technically not needed, Adobe Reader needs it
font_descriptor_vec.push(("FontBBox".into(), Array(font_bbox)));
let font_descriptor_vec_id = doc.add_object(LoDictionary::from_iter(font_descriptor_vec));
desc_fonts.set("FontDescriptor", Reference(font_descriptor_vec_id));
font_vec.push(("DescendantFonts".into(), Array(vec![Dictionary(desc_fonts)])));
font_vec.push(("ToUnicode".into(), Reference(cid_to_unicode_map_stream_id)));
LoDictionary::from_iter(font_vec)
}
}
type GlyphId = u32;
type UnicodeCodePoint = u32;
type CmapBlock = Vec<(GlyphId, UnicodeCodePoint)>;
/// Generates a CMAP (character map) from valid cmap blocks
fn generate_cid_to_unicode_map(face_name: String, all_cmap_blocks: Vec<CmapBlock>) -> String {
let mut cid_to_unicode_map = format!(include_str!("../../../../templates/gid_to_unicode_beg.txt"), face_name);
for cmap_block in all_cmap_blocks.into_iter().filter(|block| !block.is_empty() || block.len() < 100) {
cid_to_unicode_map.push_str(format!("{} beginbfchar\r\n", cmap_block.len()).as_str());
for (glyph_id, unicode) in cmap_block {
cid_to_unicode_map.push_str(format!("<{:04x}> <{:04x}>\n", glyph_id, unicode).as_str());
}
cid_to_unicode_map.push_str("endbfchar\r\n");
}
cid_to_unicode_map.push_str(include_str!("../../../../templates/gid_to_unicode_end.txt"));
cid_to_unicode_map
}
impl PartialEq for ExternalFont {
/// Two fonts are equal if their names are equal, the contents aren't checked
fn eq(&self, other: &ExternalFont) -> bool {
self.face_name == other.face_name
}
}
/// Indexed reference to a font that was added to the document
/// This is a "reference by postscript name"
#[derive(Debug, Hash, Eq, Ord, Clone, PartialEq, PartialOrd)]
pub struct IndirectFontRef {
/// Name of the font (postscript name)
pub(crate) name: String,
}
/// Direct reference (wrapper for `lopdf::Object::Reference`)
/// for increased type safety
#[derive(Debug, Clone)]
pub struct DirectFontRef {
/// Reference to the content in the document stream
pub(crate) inner_obj: lopdf::ObjectId,
/// Actual font data
pub(crate) data: Font,
}
impl IndirectFontRef {
/// Creates a new IndirectFontRef from an index
pub fn new<S>(name: S)
-> Self where S: Into<String>
{
Self {
name: name.into(),
}
}
}
/// Font list for tracking fonts within a single PDF document
#[derive(Default, Debug, Clone)]
pub struct FontList {
fonts: BTreeMap<IndirectFontRef, DirectFontRef>,
}
impl FontList {
/// Creates a new FontList
pub fn new()
-> Self
{
Self::default()
}
/// Adds a font to the FontList
pub fn add_font(&mut self, font_ref: IndirectFontRef, font: DirectFontRef)
-> IndirectFontRef
{
self.fonts.insert(font_ref.clone(), font);
font_ref
}
/// Turns an indirect font reference into a direct one
/// (Warning): clones the direct font reference
#[inline]
pub fn get_font(&self, font: &IndirectFontRef)
-> Option<DirectFontRef>
{
let font_ref = self.fonts.get(font);
if let Some(r) = font_ref {
Some(r.clone())
} else {
None
}
}
/// Returns the number of fonts currenly in use
#[inline]
pub fn len(&self)
-> usize
{
self.fonts.len()
}
/// Returns if the font list is empty
#[inline]
pub fn is_empty(&self)
-> bool
{
self.fonts.is_empty()
}
/// Converts the fonts into a dictionary
pub(crate) fn into_with_document(self, doc: &mut lopdf::Document)
->lopdf::Dictionary
{
let mut font_dict = lopdf::Dictionary::new();
for (indirect_ref, direct_font_ref) in self.fonts {
let font_dict_collected = match direct_font_ref.data {
Font::ExternalFont(font) => font.into_with_document(doc),
Font::BuiltinFont(font) => font.into(),
};
doc.objects.insert(direct_font_ref.inner_obj, lopdf::Object::Dictionary(font_dict_collected));
font_dict.set(indirect_ref.name,lopdf::Object::Reference(direct_font_ref.inner_obj));
}
font_dict
}
}
/// The unscaled base metrics for a font provided by a [`FontData`](trait.FontData.html)
/// implementation.
#[derive(Clone, Copy, Debug, Default)]
pub struct FontMetrics {
/// The ascent of the font.
pub ascent: i16,
/// The descent of the font.
pub descent: i16,
/// The units per em square for this font.
pub units_per_em: u16,
}
/// The metrics for a glyph provided by a [`FontData`](trait.FontData.html) implementation.
#[derive(Clone, Copy, Debug, Default)]
pub struct GlyphMetrics {
/// The width of the glyph, typically the horizontal advance.
pub width: u32,
/// The height of the glyph, typically the difference between the ascent and the descent.
pub height: u32,
}
/// Provides access to font metrics.
///
/// Per default, printpdf uses [`rusttype`][] to extract the font data. You can implement this
/// trait for other types if you want to use a different font backend.
///
/// [`rusttype`]: https://docs.rs/rusttype/latest/rusttype/
pub trait FontData: FontDataClone + std::fmt::Debug {
/// Returns the unscaled metrics for this font.
fn font_metrics(&self) -> FontMetrics;
/// Returns the glyph id for a Unicode character if it is present in this font.
fn glyph_id(&self, c: char) -> Option<u16>;
/// Returns a mapping from glyph IDs to Unicode characters for all supported characters.
fn glyph_ids(&self) -> std::collections::HashMap<u16, char>;
/// Returns the glyph metrics for a glyph of this font, if available.
fn glyph_metrics(&self, glyph_id: u16) -> Option<GlyphMetrics>;
}
impl FontData for rusttype::Font<'static> {
fn font_metrics(&self) -> FontMetrics {
let metrics = self.v_metrics_unscaled();
FontMetrics {
ascent: metrics.ascent as i16,
descent: metrics.descent as i16,
units_per_em: self.units_per_em(),
}
}
fn glyph_id(&self, c: char) -> Option<u16> {
let glyph_id = self.glyph(c).id().0;
if glyph_id == 0 {
None
} else {
Some(glyph_id as u16)
}
}
fn glyph_ids(&self) -> std::collections::HashMap<u16, char> {
let mut map = std::collections::HashMap::with_capacity(self.glyph_count());
for c in char::default()..std::char::MAX {
if let Some(glyph_id) = self.glyph_id(c) {
map.insert(glyph_id, c);
}
}
map
}
fn glyph_metrics(&self, glyph_id: u16) -> Option<GlyphMetrics> {
let glyph_id = rusttype::GlyphId(u32::from(glyph_id));
if let Some(glyph_metrics) = self.glyph(glyph_id).standalone().get_data() {
let width = glyph_metrics.unit_h_metrics.advance_width as u32;
let height = glyph_metrics.extents.and_then(|extents| {
let descent = self.v_metrics_unscaled().descent as i32;
Some((extents.max.y - extents.min.y - descent) as u32)
}).unwrap_or(1000);
Some(GlyphMetrics { width, height })
} else {
None
}
}
}
/// Helper trait for cloning boxed [`FontData`](trait.FontData.html) implementors.
pub trait FontDataClone {
/// Clones this font data and returns a box with the cloned data.
fn clone_font_data(&self) -> Box<dyn FontData>;
}
impl<T: FontData + Clone + 'static> FontDataClone for T {
fn clone_font_data(&self) -> Box<dyn FontData> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn FontData> {
fn clone(&self) -> Box<dyn FontData> {
self.clone_font_data()
}
}
@@ -0,0 +1,81 @@
//! Abstraction class for images.
//! Please use this class instead of adding `ImageXObjects` yourself
#[cfg(feature = "embedded_images")]
use image::{self, ImageDecoder, DynamicImage};
use Mm;
use {ImageXObject, PdfLayerReference};
/// Image - wrapper around an `ImageXObject` to allow for more control
/// within the library
#[derive(Debug)]
pub struct Image {
/// The actual image
pub image: ImageXObject,
}
impl From<ImageXObject> for Image {
fn from(image: ImageXObject)
-> Self
{
Self {
image,
}
}
}
#[cfg(feature = "embedded_images")]
impl<'a> Image {
pub fn try_from<T: ImageDecoder<'a>>(image: T)
-> Result<Self, image::ImageError>
{
let image = ImageXObject::try_from(image)?;
Ok(Self {
image,
})
}
pub fn from_dynamic_image(image: &DynamicImage)
-> Self
{
Self {
image: ImageXObject::from_dynamic_image(image),
}
}
}
impl Image {
/// Adds the image to a specific layer and consumes it
/// This is due to a PDF weirdness - images are basically just "names"
/// and you have to make sure that they are added to the same page
/// as they are used on.
///
/// You can use the "dpi" parameter to specify a scaling - the default is 300dpi
///
#[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
pub fn add_to_layer(self, layer: PdfLayerReference,
translate_x: Option<Mm>, translate_y: Option<Mm>,
rotate_cw: Option<f64>,
scale_x: Option<f64>, scale_y: Option<f64>,
dpi: Option<f64>)
{
// PDF maps an image to a 1x1 square, we have to adjust the transform matrix
// to fix the distortion
let dpi = dpi.unwrap_or(300.0);
//Image at the given dpi should 1px = 1pt
let image_w = self.image.width.into_pt(dpi);
let image_h = self.image.height.into_pt(dpi);
let image = layer.add_image(self.image);
let scale_x = scale_x.unwrap_or(1.);
let scale_y = scale_y.unwrap_or(1.);
let image_w = Some(image_w.0 * scale_x);
let image_h = Some(image_h.0 * scale_y);
layer.use_xobject(image, translate_x, translate_y, rotate_cw, image_w, image_h);
}
}
@@ -0,0 +1,156 @@
use lopdf;
use glob_defines::{
OP_PATH_CONST_MOVE_TO, OP_PATH_CONST_3BEZIER_V1, OP_PATH_CONST_3BEZIER_V2, OP_PATH_CONST_4BEZIER,
OP_PATH_CONST_LINE_TO, OP_PATH_PAINT_FILL_STROKE_CLOSE_NZ, OP_PATH_PAINT_FILL_NZ,
OP_PATH_PAINT_STROKE_CLOSE, OP_PATH_PAINT_STROKE, OP_PATH_PAINT_END, OP_PATH_CONST_CLIP_NZ,
};
use Point;
use std::iter::{FromIterator, IntoIterator};
#[derive(Debug, Clone)]
pub struct Line {
/// 2D Points for the line
pub points: Vec<(Point, bool)>,
/// Is the line closed or open?
pub is_closed: bool,
/// Should the line be filled (via winding-number rule), for polygons
pub has_fill: bool,
/// Should the line have an outline (stroke)?
pub has_stroke: bool,
/// Is this line a clipping path?
pub is_clipping_path: bool,
}
impl Default for Line {
fn default() -> Self {
Self {
points: Vec::new(),
is_closed: false,
has_fill: false,
has_stroke: false,
is_clipping_path: false,
}
}
}
impl FromIterator<(Point, bool)> for Line {
fn from_iter<I: IntoIterator<Item=(Point, bool)>>(iter: I) -> Self {
let mut points = Vec::new();
for i in iter {
points.push(i);
}
Line {
points: points,
.. Default::default()
}
}
}
impl Line {
/// Sets if the line is closed or not
#[inline]
pub fn set_closed(&mut self, is_closed: bool) {
self.is_closed = is_closed;
}
/// Sets if the line is filled
#[inline]
pub fn set_fill(&mut self, has_fill: bool) {
self.has_fill = has_fill;
}
/// Sets if the line is stroked (has an outline)
#[inline]
pub fn set_stroke(&mut self, has_stroke: bool) {
self.has_stroke = has_stroke;
}
/// Sets if the line is a clipping path
#[inline]
pub fn set_as_clipping_path(&mut self, is_clipping_path: bool) {
self.is_clipping_path = is_clipping_path;
}
pub fn into_stream_op(self)
-> Vec<lopdf::content::Operation>
{
use lopdf::content::Operation;
let mut operations = Vec::<Operation>::new();
if self.points.is_empty() { return operations; };
operations.push(Operation::new(OP_PATH_CONST_MOVE_TO, vec![self.points[0].0.x.into(), self.points[0].0.y.into()]));
// Skip first element
let mut current = 1;
let max_len = self.points.len();
// Loop over every points, determine if v, y, c or l operation should be used and build
// curve / line accordingly
while current < max_len {
let p1 = &self.points[current - 1]; // prev pt
let p2 = &self.points[current]; // current pt
if p1.1 && p2.1 {
// current point is a bezier handle
// valid bezier curve must have two sequential bezier handles
// we also can"t build a valid cubic bezier curve if the cuve contains less than
// four points. If p3 or p4 is marked as "next point is bezier handle" or not, doesn"t matter
if let Some(p3) = self.points.get(current + 1){
if let Some(p4) = self.points.get(current + 2){
if p1.0 == p2.0 {
// first control point coincides with initial point of curve
operations.push(Operation::new(OP_PATH_CONST_3BEZIER_V1, vec![p3.0.x.into(), p3.0.y.into(), p4.0.x.into(), p4.0.y.into()]));
}else if p2.0 == p3.0 {
// first control point coincides with final point of curve
operations.push(Operation::new(OP_PATH_CONST_3BEZIER_V2, vec![p2.0.x.into(), p2.0.y.into(), p4.0.x.into(), p4.0.y.into()]));
}else{
// regular bezier curve with four points
operations.push(Operation::new(OP_PATH_CONST_4BEZIER, vec![p2.0.x.into(), p2.0.y.into(), p3.0.x.into(), p3.0.y.into(), p4.0.x.into(), p4.0.y.into()]));
}
current += 3;
continue;
}
}
}
// normal straight line
operations.push(Operation::new(OP_PATH_CONST_LINE_TO, vec![p2.0.x.into(), p2.0.y.into()]));
current += 1;
}
// how to paint the path
if self.has_stroke {
if self.has_fill {
if self.is_closed {
// is filled and stroked and closed
operations.push(Operation::new(OP_PATH_PAINT_FILL_STROKE_CLOSE_NZ, vec![]));
} else {
// is filled and stroked but not closed
operations.push(Operation::new(OP_PATH_PAINT_FILL_NZ, vec![]));
}
} else if self.is_closed {
// not filled, but stroked and closed
operations.push(Operation::new(OP_PATH_PAINT_STROKE_CLOSE, vec![]));
} else {
// not filled, not closed but only stroked (regular path)
operations.push(Operation::new(OP_PATH_PAINT_STROKE, vec![]));
}
} else if self.has_fill {
// is not stroked, only filled
// closed-ness doesn't matter in this case, an area is always closed
operations.push(Operation::new(OP_PATH_PAINT_FILL_NZ, vec![]));
} else if self.is_clipping_path {
// set the path as a clipping path
operations.push(Operation::new(OP_PATH_CONST_CLIP_NZ, vec![]));
operations.push(Operation::new(OP_PATH_PAINT_END, vec![]));
} else {
// no painting operation nothing, path is invisible, only end the path
operations.push(Operation::new(OP_PATH_PAINT_END, vec![]));
}
operations
}
}
@@ -0,0 +1,13 @@
//! 2D elements for Pdf (stub), to be expanded
pub mod point;
pub mod line;
pub mod font;
// pub mod svg;
pub mod image;
pub use self::point::Point;
pub use self::line::Line;
pub use self::font::*;
// pub use self::svg::Svg;
pub use self::image::Image;
@@ -0,0 +1,42 @@
use {Mm, Pt};
#[derive(Debug, Copy, Clone)]
pub struct Point {
/// x position from the bottom left corner in pt
pub x: Pt,
/// y position from the bottom left corner in pt
pub y: Pt,
}
impl Point {
/// Create a new point.
/// **WARNING: The reference point for a point is the bottom left corner, not the top left**
#[inline]
pub fn new(x: Mm, y: Mm)
-> Self
{
Self {
x: x.into(),
y: y.into(),
}
}
}
impl PartialEq for Point {
// custom compare function because of floating point inaccuracy
fn eq(&self, other: &Point) -> bool {
if self.x.0.is_normal() && other.x.0.is_normal() &&
self.y.0.is_normal() && other.y.0.is_normal() {
// four floating point numbers have to match
let x_eq = self.x == other.x;
if !x_eq { return false; }
let y_eq = self.y == other.y;
if y_eq { return true; }
}
false
}
}
@@ -0,0 +1,178 @@
extern crate lopdf;
extern crate svg;
/// Unit for SVG elements. Uses uom crate for normalization
/// Since this library is designed to output PDFs, the only measurement
/// that PDF understands is point, so eventually everything is converted into point.
#[derive(Debug, Copy, Clone)]
pub enum SvgUnit {
/// Multiple of the total height of the first seen font (usually 16px)
/// Not yet supported, will be 16px
Em(f64),
/// Multiple of the x-height of the first seen font
/// Not yet supported, will be interpreted as x-height of the Arial font
Ex(f64),
/// Pixel
Px(f64),
/// Inch
In(f64),
/// Centimeter
Cm(f64),
/// Millimeter
Mm(f64),
/// Point
Pt(f64),
/// Percent (todo: of what?)
/// Not supported, will be interpreted as Point
Pc(f64),
}
// Should convert to points. For now, only returns the inner number
impl Into<f64> for SvgUnit {
fn into(self)
-> f64
{
use self::SvgUnit::*;
// todo!!!!!
match self {
Em(em) => 16.0 * em,
Ex(ex) => 16.0 * ex,
Px(px) => 300.0 * px,
In(inch) => 254.0 * inch,
Cm(cm) => 10.0 * 254.0 * cm,
Mm(mm) => 254.0 * mm,
Pt(pt) => pt,
Pc(pc) => pc,
}
}
}
/// SVG data
#[derive(Debug, Clone)]
pub struct Svg {
/// The actual line drawing, etc. operations, in order
operations: Vec<lopdf::content::Operation>,
/// Width of this SVG file, is None if not found
width: Option<SvgUnit>,
/// Height of this SVG file, is None if not found
height: Option<SvgUnit>,
}
impl Svg {
pub fn new<R>(svg_data: R)
-> std::result::Result<Self, ::std::io::Error> where R: ::std::io::Read
{
// use svg::node::element::path::{Command, Data};
// use svg::node::element::tag::Path;
use svg::parser::Event;
let mut initial_width = None;
let mut initial_height = None;
let parser = svg::read(svg_data)?;
// get width and height
for event in parser {
if let Event::Tag(_, _, attributes) = event {
let mut mark_break = false;
if let Some(w) = attributes.get("width") {
if let Ok(parsed_w) = w.parse::<f64>() {
initial_width = Some(SvgUnit::Pt(parsed_w));
mark_break = true;
}
}
if let Some(h) = attributes.get("height") {
if let Ok(parsed_h) = h.parse::<f64>() {
initial_height = Some(SvgUnit::Pt(parsed_h));
mark_break = true;
}
}
if mark_break { break; }
}
}
Ok( Svg {
operations: Vec::new(),
width: initial_width,
height: initial_height,
})
}
/// This is similar to the `image.add_to_layer` method, the only difference being
/// that it calls a different function
/// This should be seperated out into a macro
pub fn add_to_layer(self, layer: PdfLayerReference,
translate_x: Option<f64>, translate_y: Option<f64>,
rotate_cw: Option<f64>,
scale_x: Option<f64>, scale_y: Option<f64>)
-> std::result::Result<(), std::io::Error>
{
let svg_w: f64 = self.width.unwrap_or(SvgUnit::Pt(10.0)).into();
let svg_h: f64 = self.height.unwrap_or(SvgUnit::Pt(10.0)).into();
// add svg as XObject to page
let svg_ref = layer.add_svg(self)?;
// add reference of XObject to layer stream
if let Some(scale_x) = scale_x {
if let Some(scale_y) = scale_y {
layer.use_xobject(svg_ref, translate_x, translate_y, rotate_cw, Some(scale_x * svg_w), Some(svg_h * scale_y));
} else {
layer.use_xobject(svg_ref, translate_x, translate_y, rotate_cw, Some(scale_x * svg_w), Some(svg_h));
}
} else if let Some(scale_y) = scale_y {
layer.use_xobject(svg_ref, translate_x, translate_y, rotate_cw, Some(svg_w), Some(svg_h * scale_y));
} else {
layer.use_xobject(svg_ref, translate_x, translate_y, rotate_cw, Some(svg_w), Some(svg_h));
}
Ok(())
}
pub fn try_into(self)
-> std::result::Result<FormXObject, std::io::Error>
{
let content = lopdf::content::Content{ operations: self.operations };
let vec_u8 = content.encode()?;
Ok(FormXObject {
form_type: FormType::Type1,
bytes: vec_u8,
matrix: Some(CurTransMat::Identity),
resources: None,
group: None,
ref_dict: None,
metadata: None,
piece_info: None,
last_modified: None,
struct_parent: None,
struct_parents: None,
opi: None,
oc: None,
name: None, /* todo */
})
}
}
/// SVG `XObject`, identified by its name
#[derive(Debug)]
pub struct SvgRef {
pub(super) name: String
}
impl SvgRef {
/// Creates a new SvgRef from an index
pub fn new(index: usize)
-> Self
{
Self {
name: format!("SVG{}", index),
}
}
}
+592
View File
@@ -0,0 +1,592 @@
// clippy lints when serializing PDF strings, in this case its wrong
#![cfg_attr(feature = "cargo-clippy", allow(string_lit_as_bytes))]
use crate::OffsetDateTime;
#[cfg(feature = "embedded_images")]
use image::{DynamicImage, GenericImageView, ImageDecoder, ImageError};
use lopdf;
use std::collections::HashMap;
use {ColorBits, ColorSpace, CurTransMat, Px};
/* Parent: Resources dictionary of the page */
/// External object that gets reference outside the PDF content stream
/// Gets constructed similar to the `ExtGState`, then inserted into the `/XObject` dictionary
/// on the page. You can instantiate `XObjects` with the `/Do` operator. The `layer.add_xobject()`
/// (or better yet, the `layer.add_image()`, `layer.add_form()`) methods will do this for you.
#[derive(Debug, Clone)]
pub enum XObject {
/* /Subtype /Image */
/// Image XObject, for images
Image(ImageXObject),
/* /Subtype /Form */
/// Form XObject, for PDF forms
Form(Box<FormXObject>),
/* /Subtype /PS */
/// Embedded PostScript XObject, for legacy applications
/// You can embed PostScript in a PDF, it is not recommended
PostScript(PostScriptXObject),
}
impl XObject {
#[cfg(any(debug_assertions, feature="less-optimization"))]
#[inline]
fn compress_stream(stream: lopdf::Stream)
-> lopdf::Stream
{
stream
}
#[cfg(all(not(debug_assertions), not(feature="less-optimization")))]
#[inline]
fn compress_stream(mut stream: lopdf::Stream)
-> lopdf::Stream
{
stream.compress();
stream
}
}
impl Into<lopdf::Object> for XObject {
fn into(self)
-> lopdf::Object
{
match self {
XObject::Image(image) => { lopdf::Object::Stream(Self::compress_stream(image.into())) }
XObject::Form(form) => { let cur_form: FormXObject = *form; lopdf::Object::Stream(Self::compress_stream(cur_form.into())) }
XObject::PostScript(ps) => { lopdf::Object::Stream(Self::compress_stream(ps.into())) }
}
}
}
/// List of `XObjects`
#[derive(Debug, Default, Clone)]
pub struct XObjectList {
objects: HashMap<String, XObject>,
}
impl XObjectList {
/// Creates a new XObjectList
pub fn new()
-> Self
{
Self::default()
}
/// Adds a new XObject to the list
pub fn add_xobject(&mut self, xobj: XObject)
-> XObjectRef
{
let len = self.objects.len();
let xobj_ref = XObjectRef::new(len);
self.objects.insert(xobj_ref.name.clone(), xobj);
xobj_ref
}
/// Same as `Into<lopdf::Dictionary>`, but since the dictionary
/// items in an XObject dictionary are streams and must be added to
/// the document as __references__, this function needs an additional
/// access to the PDF document so that we can add the streams first and
/// then track the references to them.
#[cfg_attr(feature = "cargo-clippy", allow(needless_return))]
pub fn into_with_document(self, doc: &mut lopdf::Document)
-> lopdf::Dictionary
{
self.objects.into_iter().map(|(name, object)| {
let obj: lopdf::Object = object.into();
let obj_ref = doc.add_object(obj);
(name.to_string(), lopdf::Object::Reference(obj_ref))
}).collect()
}
}
/// Named reference to an `XObject`
#[derive(Debug)]
pub struct XObjectRef {
pub(crate) name: String,
}
impl XObjectRef {
/// Creates a new reference from a number
pub fn new(index: usize)
-> Self
{
Self {
name: format!("X{}", index),
}
}
}
/* todo: inline images? (icons, logos, etc.) */
/* todo: JPXDecode filter */
#[derive(Debug, Clone)]
pub struct ImageXObject {
/// Width of the image (original width, not scaled width)
pub width: Px,
/// Height of the image (original height, not scaled height)
pub height: Px,
/// Color space (Greyscale, RGB, CMYK)
pub color_space: ColorSpace,
/// Bits per color component (1, 2, 4, 8, 16) - 1 for black/white, 8 Greyscale / RGB, etc.
/// If using a JPXDecode filter (for JPEG images), this can be inferred from the image data
pub bits_per_component: ColorBits,
/// Should the image be interpolated when scaled?
pub interpolate: bool,
/// The actual data from the image
pub image_data: Vec<u8>,
/// Decompression filter for `image_data`, if `None` assumes uncompressed raw pixels in the expected color format.
pub image_filter: Option<ImageFilter>,
/* /BBox << dictionary >> */
/* todo: find out if this is really required */
/// Required bounds to clip the image, in unit space
/// Default value: Identity matrix (`[1 0 0 1 0 0]`) - used when value is `None`
pub clipping_bbox: Option<CurTransMat>,
}
impl<'a> ImageXObject {
/// Creates a new ImageXObject
// #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
#[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
pub fn new(width: Px, height: Px, color_space: ColorSpace,
bits: ColorBits, interpolate: bool, image_filter: Option<ImageFilter>,
bbox: Option<CurTransMat>, data: Vec<u8>)
-> Self
{
Self {
width,
height,
color_space,
bits_per_component: bits,
interpolate,
image_data: data,
image_filter,
clipping_bbox: bbox,
}
}
#[cfg(feature = "embedded_images")]
pub fn try_from<T: ImageDecoder<'a>>(image: T)
-> Result<Self, ImageError>
{
use std::usize;
use image::error::{LimitError, LimitErrorKind};
let dim = image.dimensions();
let color_type = image.color_type();
let num_image_bytes = image.total_bytes();
if num_image_bytes > usize::MAX as u64{
return Err(ImageError::Limits(LimitError::from_kind(LimitErrorKind::InsufficientMemory)));
}
let mut image_data = vec![0;num_image_bytes as usize];
image.read_image(&mut image_data)?;
let color_bits = ColorBits::from(color_type);
let color_space = ColorSpace::from(color_type);
Ok(Self {
width: Px(dim.0 as usize),
height: Px(dim.1 as usize),
color_space: color_space,
bits_per_component: color_bits,
image_data,
interpolate: true,
image_filter: None,
clipping_bbox: None,
})
}
#[cfg(feature = "embedded_images")]
pub fn from_dynamic_image(image: &DynamicImage)
-> Self
{
let dim = image.dimensions();
let color_type = image.color();
let data = image.to_bytes();
let color_bits = ColorBits::from(color_type);
let color_space = ColorSpace::from(color_type);
Self {
width: Px(dim.0 as usize),
height: Px(dim.1 as usize),
color_space: color_space,
bits_per_component: color_bits,
image_data: data,
interpolate: true,
image_filter: None,
clipping_bbox: None,
}
}
}
impl Into<lopdf::Stream> for ImageXObject {
fn into(self)
-> lopdf::Stream
{
use lopdf::Object::*;
use std::iter::FromIterator;
let cs: &'static str = self.color_space.into();
let bbox: lopdf::Object = self.clipping_bbox
.unwrap_or(CurTransMat::Identity)
.into();
let mut dict = lopdf::Dictionary::from_iter(vec![
("Type", Name("XObject".as_bytes().to_vec())),
("Subtype", Name("Image".as_bytes().to_vec())),
("Width", Integer(self.width.0 as i64)),
("Height", Integer(self.height.0 as i64)),
("Interpolate", self.interpolate.into()),
("BitsPerComponent", Integer(self.bits_per_component.into())),
("ColorSpace", Name(cs.as_bytes().to_vec())),
("BBox", bbox),
]);
if let Some(filter) = self.image_filter {
let params = match filter {
// TODO technically we could use multiple filters,
// DCT as an exception!
ImageFilter::DCT => {
vec![
("Filter", Array(vec![Name("DCTDecode".as_bytes().to_vec())])),
// not necessary, unless missing in the jpeg header
("DecodeParams", Dictionary(lopdf::dictionary!("ColorTransform" => Integer(0)))),
]
},
_ => unimplemented!("Encountered filter type is not supported"),
};
params.into_iter().for_each(|param| dict.set(param.0, param.1));
}
lopdf::Stream::new(dict, self.image_data)
}
}
/// Named reference to an image
#[derive(Debug)]
pub struct ImageXObjectRef {
name: String,
}
/// Describes the format the image bytes are compressed with.
#[derive(Debug, Copy, Clone)]
pub enum ImageFilter {
/// ???
Ascii85,
/// Lempel Ziv Welch compression, i.e. zip
Lzw,
/// Discrete Cosinus Transform, JPEG Baseline.
DCT,
/// JPEG2000 aka JPX wavelet based compression.
JPX,
}
/// __THIS IS NOT A PDF FORM!__ A form `XObject` can be nearly everything.
/// PDF allows you to reuse content for the graphics stream in a `FormXObject`.
/// A `FormXObject` is basically a layer-like content stream and can contain anything
/// as long as it's a valid strem. A `FormXObject` is intended to be used for reapeated
/// content on one page.
#[derive(Debug, Clone)]
pub struct FormXObject {
/* /Type /XObject */
/* /Subtype /Form */
/* /FormType Integer */
/// Form type (currently only Type1)
pub form_type: FormType,
/// The actual content of this FormXObject
pub bytes: Vec<u8>,
/* /Matrix [Integer , 6] */
/// Optional matrix, maps the form into user space
pub matrix: Option<CurTransMat>,
/* /Resources << dictionary >> */
/// (Optional but strongly recommended; PDF 1.2) A dictionary specifying
/// any resources (such as fonts and images) required by the form XObject
/// (see Section 3.7, “Content Streams and Resources”).
///
/// In PDF 1.1 and earlier, all named resources used in the form XObject must be
/// included in the resource dictionary of each page object on which the form
/// XObject appears, regardless of whether they also appear in the resource
/// dictionary of the form XObject. It can be useful to specify these resources
/// in the form XObject’s resource dictionary as well, to determine which resources
/// are used inside the form XObject. If a resource is included in both dictionaries,
/// it should have the same name in both locations.
/// /// In PDF 1.2 and later versions, form XObjects can be independent of the content
/// streams in which they appear, and this is strongly recommended although not
/// required. In an independent form XObject, the resource dictionary of the form
/// XObject is required and contains all named resources used by the form XObject.
/// These resources are not promoted to the outer content stream’s resource
/// dictionary, although that stream’s resource dictionary refers to the form XObject.
pub resources: Option<lopdf::Dictionary>,
/* /Group << dictionary >> */
/// (Optional; PDF 1.4) A group attributes dictionary indicating that the contents of the
/// form XObject are to be treated as a group and specifying the attributes of that group
/// (see Section 4.9.2, “Group XObjects”).
///
/// Note: If a Ref entry (see below) is present, the group attributes also apply to the
/// external page imported by that entry, which allows such an imported page to be treated
/// as a group without further modification.
pub group: Option<GroupXObject>,
/* /Ref << dictionary >> */
/// (Optional; PDF 1.4) A reference dictionary identifying a page to be imported from another
/// PDF file, and for which the form XObject serves as a proxy (see Section 4.9.3, “Reference XObjects”).
pub ref_dict: Option<lopdf::Dictionary>,
/* /Metadata [stream] */
/// (Optional; PDF 1.4) A metadata stream containing metadata for the form XObject
/// (see Section 10.2.2, “Metadata Streams”).
pub metadata: Option<lopdf::Stream>,
/* /PieceInfo << dictionary >> */
/// (Optional; PDF 1.3) A page-piece dictionary associated with the form XObject
/// (see Section 10.4, “Page-Piece Dictionaries”).
pub piece_info: Option<lopdf::Dictionary>,
/* /LastModified (date) */
/// (Required if PieceInfo is present; optional otherwise; PDF 1.3) The date and time
/// (see Section 3.8.3, “Dates”) when the form XObject’s contents were most recently
/// modified. If a page-piece dictionary (PieceInfo) is present, the modification date
/// is used to ascertain which of the application data dictionaries it contains correspond
/// to the current content of the form (see Section 10.4, “Page-Piece Dictionaries”).
pub last_modified: Option<OffsetDateTime>,
/* /StructParent integer */
/// (Required if the form XObject is a structural content item; PDF 1.3) The integer key of
/// the form XObject’s entry in the structural parent tree (see “Finding Structure Elements
/// from Content Items” on page 868).
pub struct_parent: Option<i64>,
/* /StructParents integer */
/// __(Required if the form XObject contains marked-content sequences that are structural content
/// items; PDF 1.3)__ The integer key of the form XObject’s entry in the structural parent tree
/// (see “Finding Structure Elements from Content Items” on page 868).
///
/// __Note:__ At most one of the entries StructParent or StructParents may be present. A form
/// XObject can be either a content item in its entirety or a container for marked-content sequences
/// that are content items, but not both.
pub struct_parents: Option<i64>,
/* /OPI << dictionary >> */
/// (Optional; PDF 1.2) An OPI version dictionary for the form XObject
/// (see Section 10.10.6, “Open Prepress Interface (OPI)”).
pub opi: Option<lopdf::Dictionary>,
/// (Optional; PDF 1.5) An optional content group or optional content membership dictionary
/// (see Section 4.10, “Optional Content”) specifying the optional content properties for
/// the form XObject. Before the form is processed, its visibility is determined based on
/// this entry. If it is determined to be invisible, the entire form is skipped, as if there
/// were no Do operator to invoke it.
pub oc: Option<lopdf::Dictionary>,
/* /Name /MyName */
/// __(Required in PDF 1.0; optional otherwise)__ The name by which this form XObject is referenced
/// in the XObject subdictionary of the current resource dictionary
/// (see Section 3.7.2, “Resource Dictionaries”).
/// __Note:__ This entry is obsolescent and its use is no longer recommended.
/// (See implementation note 55 in Appendix H.)
pub name: Option<String>,
}
impl Into<lopdf::Stream> for FormXObject {
fn into(self)
-> lopdf::Stream
{
use std::iter::FromIterator;
use lopdf::Object::*;
let dict = lopdf::Dictionary::from_iter(vec![
("Type", Name("XObject".as_bytes().to_vec())),
("Subtype", Name("Form".as_bytes().to_vec())),
("FormType", Integer(self.form_type.into())),
]);
lopdf::Stream::new(dict, self.bytes)
}
}
/*
<<
/Type /XObject
/Subtype /Form
/FormType 1
/BBox [ 0 0 1000 1000 ]
/Matrix [ 1 0 0 1 0 0 ]
/Resources << /ProcSet [ /PDF ] >>
/Length 58
>>
*/
#[derive(Debug, Clone)]
pub struct FormXObjectRef {
name: String,
}
#[derive(Debug, Copy, Clone)]
pub enum FormType {
/// The only form type ever declared by Adobe
/* Integer(1) */
Type1,
}
impl Into<i64> for FormType {
fn into(self)
-> i64
{
match self {
FormType::Type1 => 1,
}
}
}
/*
see page 341
/Type /Image1
/Subtype /Image
/Width 350
/Height 200
/ColorSpace /DeviceRGB % required, except for JPXDecode, not allowed for image masks
/BitsPerComponent 8 % if ImageMask is true, optional or 1.
% Optional stuff below
/Intent /RelativeColormetric
/ImageMask false % Mask and ColorSpace should not be specified
/Mask << >> % Stream or array of colors to be masked
/Decode [0 1] % weird
/Interpolate true
/Alternate [] % array of alternative images
/SMask << >> % (Optional; PDF 1.4) A subsidiary image XObject defining a soft-mask image
% (see “Soft-Mask Images” on page 553) to be used as a source of mask shape
% or mask opacity values in the transparent imaging model. The alpha source
% parameter in the graphics state determines whether the mask values are
% interpreted as shape or opacity.
% If present, this entry overrides the current soft mask in the graphics state,
% as well as the image’s Mask entry, if any. (However, the other
% transparency-related graphics state parameters—blend mode and alpha
% constant—remain in effect.) If SMask is absent, the image has no associated
% soft mask (although the current soft mask in the graphics state may still apply).
/SMaskInData % 0, 1, 2
/Matte % if present, the SMask must have the same w / h as the picture.
*/
/* Parent: XObject with /Subtype /Image */
/// `SMask` dictionary. A soft mask (or `SMask`) is a greyscale image
/// that is used to mask another image
#[derive(Debug)]
pub struct SMask {
/* /Type /XObject */
/* /Subtype /Image */
/* /ColorSpace /DeviceGray */
/* /Intent (is ignored, don't set) */
/* /ImageMask (fals or not set, is ignored, don't set) */
/* /Mask (must be absent) */
/* /SMask (must be absent) */
/* /Decode (must be [0 1]) */
/* /Alternates (ignored, don't set) */
/* /Name (ignored, don't set) */
/* /StructParent (ignored, don't set) */
/* /ID (ignored, don't set) */
/* /OPI (ignored, don't set) */
/// If `self.matte` is set to true, this entry must be the same
/// width as the parent image. If not, the `SMask` is resampled to the parent unit square
pub width: i64,
/// See width
pub height: i64,
/* /Interpolate (optional, set to true)*/
pub interpolate: bool,
/// Bits per component, required (warning: this is a grayscale image)
pub bits_per_component: i64,
/// Vec of component values
pub matte: Vec<i64>,
}
// in the PDF content stream, reference an XObject like this
/*
q % Save graphics state
1 0 0 1 100 200 cm % Translate
0. 7071 0. 7071 −0. 7071 0. 7071 0 0 cm % Rotate
150 0 0 80 0 0 cm % Scale
/Image1 Do % Paint image
Q % Restore graphics state
*/
#[derive(Debug, Copy, Clone)]
pub struct GroupXObject {
/* /Type /Group */
/* /S /Transparency */ /* currently the only valid GroupXObject */
}
#[derive(Debug, Copy, Clone)]
pub enum GroupXObjectType {
/// Transparency group XObject
TransparencyGroup,
}
/// PDF 1.4 and higher
/// Contains a PDF file to be embedded in the current PDF
#[derive(Debug)]
pub struct ReferenceXObject {
/// (Required) The file containing the target document. (?)
pub file: Vec<u8>,
/// Page number to embed
pub page: i64,
/// Optional, should be the document ID and version ID from the metadata
pub id: [i64; 2],
}
/* parent: Catalog dictionary, I think, not sure */
/// Optional content group, for PDF layers. Only available in PDF 1.4
/// but (I think) lower versions of PDF allow this, too. Used to create
/// Adobe Illustrator-like layers in PDF
#[derive(Debug)]
pub struct OptionalContentGroup {
/* /Type /OCG */
/* /Name (Layer 1) */
/// (Required) The name of the optional content group, suitable for
/// presentation in a viewer application’s user interface.
pub name: String,
/* /Intent [/View /Design] */
/// (Optional) A single intent name or an array containing any
/// combination of names. PDF 1.5 defines two names, View and Design,
/// that indicate the intended use of the graphics in the group.
/// Future versions may define others. A processing application can choose
/// to use only groups that have a specific intent and ignore others.
/// Default value: View. See “Intent” on page 368 for more information.
pub intent: Vec<OCGIntent>,
/* /Usage << dictionary >> */
/// (Optional) A usage dictionary describing the nature of the content controlled
/// by the group. It may be used by features that automatically control the state
/// of the group based on outside factors. See “Usage and Usage Application
/// Dictionaries” on page 380 for more information.
pub usage: Option<lopdf::Dictionary>,
}
/// Intent to use for the optional content groups
#[derive(Debug, Copy, Clone)]
pub enum OCGIntent {
View,
Design,
}
/// TODO, very low priority
#[derive(Debug, Clone)]
pub struct PostScriptXObject {
/// __(Optional)__ A stream whose contents are to be used in
/// place of the PostScript XObject’s stream when the target
/// PostScript interpreter is known to support only LanguageLevel 1
level1: Option<Vec<u8>>,
}
impl Into<lopdf::Stream> for PostScriptXObject {
fn into(self)
-> lopdf::Stream
{
// todo!
lopdf::Stream::new(lopdf::Dictionary::new(), Vec::new())
}
}
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
//! Interactive elements such a comment / annotation, etc.
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
//! Audio can be embedded in Pdf
+4
View File
@@ -0,0 +1,4 @@
//! Audio / Video should go here (currently stub)
pub mod audio;
pub mod video;
+1
View File
@@ -0,0 +1 @@
//! Video can be embedded in Pdf.
+111
View File
@@ -0,0 +1,111 @@
//! Info dictionary of a PDF document
use crate::OffsetDateTime;
use lopdf;
use PdfConformance;
/// "Info" dictionary of a PDF document.
/// Actual data is contained in `DocumentMetadata`, to keep it in sync with the `XmpMetadata`
/// (if the timestamps / settings are not in sync, Preflight will complain)
#[derive(Default, Debug, Copy, Clone)]
pub struct DocumentInfo {
// DocumentInfo is older than XmpMetadata
// The following is a list of things available to the DocumentInfo dictionary.
// These keys don't have to be set:
/*
/Author ( Craig J. Hogan )
/Subject ( doi:10.1038/445037a )
/Keywords ( cosmology infrared protogalaxy starlight )
/Identifier ( doi:10.1038/445037a )
/Creator ( … )
/Producer ( … )
*/
// The more modern approach is to put them into the XmpMetadata struct:
// This struct is merely a wrapper around those types that HAVE to be in a PDF/X-conform
// document.
/*
<rdf:Description rdf:about=“” xmlns:dc=“http://purl.org/dc/elements/1.1/">
<dc:creator>Craig J. Hogan</dc:creator>
<dc:title>Cosmology: Ripples of early starlight</dc:title>
<dc:identifier>doi:10.1038/445037a</dc:identifier>
<dc:source>Nature 445, 37 (2007)</dc:source>
<dc:date>2007-01-04</dc:date>
<dc:format>application/pdf</dc:format>
<dc:publisher>Nature Publishing Group</dc:publisher>
<dc:language>en<dc:language>
<dc:rights>© 2007 Nature Publishing Group</dc:rights>
</rdf:Description>
<rdf:Description rdf:about=“” xmlns:prism=“http://prismstandard.org/namespaces/1.2/basic/">
<prism:publicationName>Nature</prism:publicationName>
<prism:issn>0028-0836</prism:issn>
<prism:eIssn>1476-4679</prism:eIssn>
<prism:publicationDate>2007-01-04</prism:publicationDate>
<prism:copyright>© 2007 Nature Publishing Group</prism:copyright>
<prism:rightsAgent>permissions@nature.com</prism:rightsAgent>
<prism:volume>445</prism:volume> <prism:number>7123</prism:number>
<prism:startingPage>37</prism:startingPage>
<prism:endingPage>37</prism:endingPage>
<prism:section>News and Views</prism:section>
</rdf:Description>
*/
}
impl DocumentInfo {
/// Create a new doucment info dictionary from a document
pub fn new()
-> Self
{
Self::default()
}
/// This functions is similar to the IntoPdfObject trait method,
/// but takes additional arguments in order to delay the setting
pub(in types) fn into_obj<S>(self,
document_title: S,
trapping: bool,
conformance: PdfConformance,
creation_date: OffsetDateTime,
modification_date: OffsetDateTime)
-> lopdf::Object where S: Into<String>
{
use lopdf::Dictionary as LoDictionary;
use lopdf::Object::*;
use lopdf::StringFormat::Literal;
use std::iter::FromIterator;
let trapping = if trapping { "True" } else { "False" };
let gts_pdfx_version = conformance.get_identifier_string();
let info_mod_date = to_pdf_time_stamp_metadata(modification_date);
let info_create_date = to_pdf_time_stamp_metadata(creation_date);
Dictionary(LoDictionary::from_iter(vec![
("Trapped", trapping.into()),
("CreationDate", String(info_create_date.into_bytes(), Literal)),
("ModDate", String(info_mod_date.into_bytes(), Literal)),
("GTS_PDFXVersion", String(gts_pdfx_version.into(), Literal)),
("Title", String(document_title.into().as_bytes().to_vec(), Literal))
]))
}
}
// D:20170505150224+02'00'
fn to_pdf_time_stamp_metadata(date: OffsetDateTime)
-> String
{
// Since the time is in UTC, we know that the time zone
// difference to UTC is 0 min, 0 sec, hence the 00'00
format!("D:{:04}{:02}{:02}{:02}{:02}{:02}+00'00'",
date.year(),
date.month(),
date.day(),
date.hour(),
date.minute(),
date.second(),
)
}
+2
View File
@@ -0,0 +1,2 @@
//! Other PDF objects that should have their own module, but don't belong into any other category
pub mod document_info;
+16
View File
@@ -0,0 +1,16 @@
//! Any kind of PDF objects. Every object that can be added to the PDF is a "plugin".
//!
//! Plugins are type that do not have to do with the core structure of PDF
//! (such as pagination, etc) but are "extensions" to the core PDF model.
//!
//! They can range from simple (graphics, video, audio, annotations, etc.)
//!
//! A public-facing plugin must implement `IntoPdfObject`. Internally, a plugin
//! may consist of sub-plugins (for example stream objects).
pub mod graphics;
pub mod media;
pub mod interactive;
pub mod xmp;
pub mod misc;
pub mod security;
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
pub mod encrypt;
pub mod password;
pub mod signature;
Whitespace-only changes.
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
pub mod xmp_metadata;
+93
View File
@@ -0,0 +1,93 @@
//! Stub plugin for XMP Metadata streams, to be expanded later
use crate::OffsetDateTime;
use lopdf;
use PdfConformance;
use utils::random_character_string_32;
/// Initial struct for Xmp metatdata. This should be expanded later for XML handling, etc.
/// Right now it just fills out the necessary fields
#[derive(Debug, Clone)]
pub struct XmpMetadata {
/// Document ID
pub document_id: String,
/// Web-viewable or "default" or to be left empty. Usually "default".
pub rendition_class: Option<String>,
/// Document version
pub document_version: u32,
}
impl XmpMetadata {
/// Creates a new XmpMetadata object
pub fn new(rendition_class: Option<String>, document_version: u32)
-> Self
{
let document_id: String = random_character_string_32();
Self {
document_id: document_id,
rendition_class: rendition_class,
document_version: document_version,
}
}
/// Consumes the XmpMetadata and turns it into a PDF Object.
/// This is similar to the
pub(in types) fn into_obj<S>(self,
conformance: PdfConformance,
trapping: bool,
creation_date: OffsetDateTime,
modification_date: OffsetDateTime,
metadata_date: OffsetDateTime,
document_title: S)
-> lopdf::Object where S: Into<String> + ::std::fmt::Display
{
use lopdf::{Stream as LoStream, Dictionary as LoDictionary};
use lopdf::Object::*;
use std::iter::FromIterator;
// Shared between XmpMetadata and DocumentInfo
let trapping = if trapping { "True" } else { "False" };
// let xmp_instance_id = "2898d852-f86f-4479-955b-804d81046b19";
let instance_id = random_character_string_32();
let create_date = to_pdf_xmp_date(creation_date);
let modification_date = to_pdf_xmp_date(modification_date);
let metadata_date = to_pdf_xmp_date(metadata_date);
let pdf_x_version = conformance.get_identifier_string();
let document_version = self.document_version.to_string();
let document_id = self.document_id.to_string();
let rendition_class = match self.rendition_class {
Some(class) => class,
None => "".to_string(),
};
let xmp_metadata = format!(include_str!("../../../templates/catalog_xmp_metadata.txt"),
create_date, modification_date, metadata_date, document_title, document_id,
instance_id, rendition_class, document_version, pdf_x_version, trapping);
Stream(LoStream::new(LoDictionary::from_iter(vec![
("Type", "Metadata".into()),
("Subtype", "XML".into()), ]),
xmp_metadata.as_bytes().to_vec() ))
}
}
// D:2018-09-19T10:05:05+00'00'
fn to_pdf_xmp_date(date: OffsetDateTime)
-> String
{
// Since the time is in UTC, we know that the time zone
// difference to UTC is 0 min, 0 sec, hence the 00'00
format!("D:{:04}-{:02}-{:02}T{:02}:{:02}:{:02}+00'00'",
date.year(),
date.month(),
date.day(),
date.hour(),
date.minute(),
date.second(),
)
}
+133
View File
@@ -0,0 +1,133 @@
//! Utility / conveniece functions for commonly use graphical shapes
use scale::Pt;
use Point;
// PDF doesn't understand what a "circle" is, so we have to
// approximate it.
const C: f64 = 0.551915024494;
/// Calculates and returns the points for an approximated circle, given a radius and an
/// offset into the page from the lower left corner.
#[inline]
pub fn calculate_points_for_circle<P: Into<Pt>>(
radius: P,
offset_x: P,
offset_y: P,
) -> Vec<(Point, bool)> {
let (radius, offset_x, offset_y) = (radius.into(), offset_x.into(), offset_y.into());
let radius = radius.0;
let p10 = Point { x: Pt(0.0 * radius), y: Pt(1.0 * radius) };
let p11 = Point { x: Pt(C * radius), y: Pt(1.0 * radius) };
let p12 = Point { x: Pt(1.0 * radius), y: Pt(C * radius) };
let p13 = Point { x: Pt(1.0 * radius), y: Pt(0.0 * radius) };
let p20 = Point { x: Pt(1.0 * radius), y: Pt(0.0 * radius) };
let p21 = Point { x: Pt(1.0 * radius), y: Pt(-C * radius) };
let p22 = Point { x: Pt(C * radius), y: Pt(-1.0 * radius) };
let p23 = Point { x: Pt(0.0 * radius), y: Pt(-1.0 * radius) };
let p30 = Point { x: Pt(0.0 * radius), y: Pt(-1.0 * radius) };
let p31 = Point { x: Pt(-C * radius), y: Pt(-1.0 * radius) };
let p32 = Point { x: Pt(-1.0 * radius), y: Pt(-C * radius) };
let p33 = Point { x: Pt(-1.0 * radius), y: Pt(0.0 * radius) };
let p40 = Point { x: Pt(-1.0 * radius), y: Pt(0.0 * radius) };
let p41 = Point { x: Pt(-1.0 * radius), y: Pt(C * radius) };
let p42 = Point { x: Pt(-C * radius), y: Pt(1.0 * radius) };
let p43 = Point { x: Pt(0.0 * radius), y: Pt(1.0 * radius) };
let mut pts = vec![(p10, true), (p11, true), (p12, true), (p13, false),
(p20, true), (p21, true), (p22, true), (p23, false),
(p30, true), (p31, true), (p32, true), (p33, false),
(p40, true), (p41, true), (p42, true), (p43, false),
];
for &mut (ref mut p, _) in pts.iter_mut() {
p.x.0 += offset_x.0;
p.y.0 += offset_y.0;
}
pts
}
/// Calculates and returns the points for a rectangle, given a horizontal and vertical scale,
/// and an offset into the page from the lower left corner.
#[inline]
pub fn calculate_points_for_rect<P: Into<Pt>>(
scale_x: P,
scale_y: P,
offset_x: P,
offset_y: P,
) -> Vec<(Point, bool)> {
let (scale_x, scale_y, offset_x, offset_y) = (
scale_x.into(),
scale_y.into(),
offset_x.into(),
offset_y.into(),
);
let top = Pt(offset_y.0 + (scale_y.0 / 2.0));
let bottom = Pt(offset_y.0 - (scale_y.0 / 2.0));
let left = Pt(offset_x.0 - (scale_x.0 / 2.0));
let right = Pt(offset_x.0 + (scale_x.0 / 2.0));
let top_left_pt = Point { x: left, y: top };
let top_right_pt = Point { x: right, y: top };
let bottom_right_pt = Point { x: right, y: bottom };
let bottom_left_pt = Point { x: left, y: bottom };
vec![(top_left_pt, false), (top_right_pt, false), (bottom_right_pt, false), (bottom_left_pt, false)]
}
use std::sync::atomic::{AtomicUsize, Ordering};
/// Since the random number generator doesn't have to be cryptographically secure
/// it doesn't make sense to import the entire rand library, so this is just a
/// xorshift pseudo-random function
static RAND_SEED: AtomicUsize = AtomicUsize::new(2100);
/// Xorshift-based random number generator. Impure function
pub(crate) fn rand() -> usize {
let mut x = RAND_SEED.fetch_add(21, Ordering::SeqCst);
#[cfg(target_pointer_width = "64")] {
x ^= x << 21;
x ^= x >> 35;
x ^= x << 4;
x
}
#[cfg(target_pointer_width = "32")] {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
x
}
}
/// Returns a string with 32 random characters
pub(crate) fn random_character_string_32() -> String {
const MAX_CHARS: usize = 32;
let mut final_string = String::with_capacity(MAX_CHARS);
let mut char_pos = 0;
'outer: while char_pos < MAX_CHARS {
let rand = format!("{}", rand());
for ch in rand.chars() {
if char_pos < MAX_CHARS {
final_string.push(u8_to_char(ch.to_digit(10).unwrap() as u8));
char_pos += 1;
} else {
break 'outer;
}
}
}
final_string
}
#[inline(always)]
fn u8_to_char(input: u8) -> char {
('A' as u8 + input) as char
}