Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(pdf): render searchable PDFs with Krilla

ldm053d16780d5d4
diff --git a/Cargo.lock b/Cargo.lock
index 857ff3e13..e8920c62a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aes"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58"
+dependencies = [
+ "cipher",
+ "cpubits",
+ "cpufeatures 0.3.0",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -23,6 +34,15 @@ version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
+[[package]]
+name = "alloc-stdlib"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
+dependencies = [
+ "alloc-no-stdlib",
+]
+
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -305,9 +325,9 @@ dependencies = [
[[package]]
name = "bitflags"
-version = "2.11.0"
+version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
@@ -327,6 +347,15 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "block-padding"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "bon"
version = "3.9.3"
@@ -369,6 +398,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
+ "alloc-stdlib",
]
[[package]]
@@ -452,6 +482,15 @@ dependencies = [
"rustversion",
]
+[[package]]
+name = "cbc"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.2.57"
@@ -470,7 +509,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
- "nom",
+ "nom 7.1.3",
]
[[package]]
@@ -479,6 +518,17 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "charset"
version = "0.1.5"
@@ -533,6 +583,16 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "579504560394e388085d0c080ea587dfa5c15f7e251b4d5247d1e1a61d1d6928"
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "crypto-common 0.2.2",
+ "inout",
+]
+
[[package]]
name = "clang-sys"
version = "1.8.1"
@@ -1079,6 +1139,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer 0.12.1",
+ "const-oid",
"crypto-common 0.2.2",
]
@@ -1170,6 +1231,15 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+[[package]]
+name = "ecb"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "ed448"
version = "0.5.0"
@@ -1342,6 +1412,9 @@ name = "float-cmp"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+dependencies = [
+ "num-traits",
+]
[[package]]
name = "fnv"
@@ -1355,6 +1428,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "font-types"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "font-types"
version = "0.12.1"
@@ -1405,7 +1487,7 @@ dependencies = [
"objc2-core-text",
"objc2-foundation",
"parlance",
- "read-fonts",
+ "read-fonts 0.41.0",
"roxmltree 0.21.1",
"smallvec",
"windows",
@@ -1552,10 +1634,22 @@ checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"libc",
- "r-efi",
+ "r-efi 5.3.0",
"wasip2",
]
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "gif"
version = "0.14.2"
@@ -1563,7 +1657,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
dependencies = [
"color_quant",
- "weezl",
+ "weezl 0.1.12",
]
[[package]]
@@ -1578,7 +1672,7 @@ dependencies = [
"log",
"peniko",
"png",
- "skrifa",
+ "skrifa 0.44.0",
"smallvec",
"vello_common",
]
@@ -1645,7 +1739,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags",
"bytemuck",
- "read-fonts",
+ "read-fonts 0.41.0",
"smallvec",
]
@@ -2041,6 +2135,12 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "imagesize"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
+
[[package]]
name = "imagesize"
version = "0.15.0"
@@ -2075,6 +2175,16 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "block-padding",
+ "hybrid-array",
+]
+
[[package]]
name = "integer-encoding"
version = "3.0.4"
@@ -2162,6 +2272,33 @@ dependencies = [
"cpufeatures 0.3.0",
]
+[[package]]
+name = "krilla"
+version = "0.8.2"
+source = "git+https://github.com/LaurenzV/krilla?rev=5eb4e1fb24a24ce78b533c23b080969917530c32#5eb4e1fb24a24ce78b533c23b080969917530c32"
+dependencies = [
+ "base64 0.22.1",
+ "bumpalo",
+ "crc32fast",
+ "flate2",
+ "float-cmp",
+ "gif",
+ "image-webp",
+ "imagesize 0.14.0",
+ "indexmap",
+ "pdf-writer",
+ "png",
+ "rustc-hash 2.1.1",
+ "siphasher",
+ "skrifa 0.44.0",
+ "smallvec",
+ "subsetter",
+ "tiny-skia-path",
+ "xmp-writer",
+ "yoke",
+ "zune-jpeg",
+]
+
[[package]]
name = "kurbo"
version = "0.13.1"
@@ -2289,6 +2426,33 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+[[package]]
+name = "lopdf"
+version = "0.45.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3"
+dependencies = [
+ "aes",
+ "bitflags",
+ "brotli-decompressor",
+ "cbc",
+ "ecb",
+ "encoding_rs",
+ "flate2",
+ "getrandom 0.4.3",
+ "indexmap",
+ "itoa",
+ "log",
+ "md-5",
+ "nom 8.0.0",
+ "rand 0.10.3",
+ "rangemap",
+ "sha2",
+ "stringprep",
+ "thiserror",
+ "weezl 0.2.1",
+]
+
[[package]]
name = "malloc_size_of_derive"
version = "0.1.3"
@@ -2338,6 +2502,16 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+[[package]]
+name = "md-5"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
+dependencies = [
+ "cfg-if",
+ "digest 0.11.3",
+]
+
[[package]]
name = "memchr"
version = "2.8.0"
@@ -2396,6 +2570,7 @@ dependencies = [
"cidr",
"clap",
"libc",
+ "lopdf",
"moli-browser-profile",
"moli-cookie-cache",
"moli-cookie-import",
@@ -2813,7 +2988,7 @@ dependencies = [
"moli-image",
"moli-system-fonts",
"parley",
- "read-fonts",
+ "read-fonts 0.41.0",
"stylo",
"stylo_taffy",
"taffy",
@@ -2920,9 +3095,12 @@ dependencies = [
"anyrender",
"anyrender_svg",
"anyrender_vello_cpu",
+ "krilla",
+ "lopdf",
"moli-image",
"moli-layout",
"peniko",
+ "skrifa 0.44.0",
]
[[package]]
@@ -2969,6 +3147,7 @@ dependencies = [
"futures-util",
"http",
"indexmap",
+ "lopdf",
"moli-bounded-buffer",
"moli-browser-profile",
"moli-cookie-jar",
@@ -2979,7 +3158,9 @@ dependencies = [
"moli-fetch",
"moli-header-field",
"moli-image",
+ "moli-layout",
"moli-page-types",
+ "moli-paint",
"moli-protocol-cdp",
"moli-session-history",
"moli-shared-worker",
@@ -3096,6 +3277,7 @@ dependencies = [
"httpdate",
"indexmap",
"kurbo",
+ "lopdf",
"markup5ever",
"moli-action-window",
"moli-broadcast-channel",
@@ -3573,6 +3755,15 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "nonmax"
version = "0.5.5"
@@ -4045,7 +4236,7 @@ dependencies = [
"parlance",
"parley_data",
"parley_emoji",
- "skrifa",
+ "skrifa 0.44.0",
]
[[package]]
@@ -4054,6 +4245,17 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+[[package]]
+name = "pdf-writer"
+version = "0.15.0"
+source = "git+https://github.com/typst/pdf-writer?rev=fdf090125f1e7209fa630c4ca1f5f29910c87c93#fdf090125f1e7209fa630c4ca1f5f29910c87c93"
+dependencies = [
+ "bitflags",
+ "itoa",
+ "memchr",
+ "ryu",
+]
+
[[package]]
name = "pem"
version = "3.0.6"
@@ -4299,6 +4501,12 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
[[package]]
name = "rand"
version = "0.8.8"
@@ -4320,6 +4528,17 @@ dependencies = [
"rand_core 0.9.5",
]
+[[package]]
+name = "rand"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "rand_chacha"
version = "0.3.1"
@@ -4364,6 +4583,12 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+[[package]]
+name = "rangemap"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
+
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -4403,6 +4628,16 @@ dependencies = [
"yasna",
]
+[[package]]
+name = "read-fonts"
+version = "0.39.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
+dependencies = [
+ "bytemuck",
+ "font-types 0.11.3",
+]
+
[[package]]
name = "read-fonts"
version = "0.41.0"
@@ -4410,7 +4645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
- "font-types",
+ "font-types 0.12.1",
"once_cell",
]
@@ -4831,6 +5066,17 @@ dependencies = [
"digest 0.10.7",
]
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "digest 0.11.3",
+]
+
[[package]]
name = "shake"
version = "0.1.0"
@@ -4898,6 +5144,16 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"
+[[package]]
+name = "skrifa"
+version = "0.42.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
+dependencies = [
+ "bytemuck",
+ "read-fonts 0.39.2",
+]
+
[[package]]
name = "skrifa"
version = "0.44.0"
@@ -4905,7 +5161,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
- "read-fonts",
+ "read-fonts 0.41.0",
]
[[package]]
@@ -5040,6 +5296,17 @@ dependencies = [
"quote",
]
+[[package]]
+name = "stringprep"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+ "unicode-properties",
+]
+
[[package]]
name = "strip-ansi-escapes"
version = "0.2.1"
@@ -5218,6 +5485,18 @@ dependencies = [
"url",
]
+[[package]]
+name = "subsetter"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
+dependencies = [
+ "kurbo",
+ "rustc-hash 2.1.1",
+ "skrifa 0.42.1",
+ "write-fonts",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -5799,6 +6078,21 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
+[[package]]
+name = "unicode-normalization"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "unicode-properties"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
+
[[package]]
name = "unicode-script"
version = "0.5.8"
@@ -5852,14 +6146,14 @@ dependencies = [
"flate2",
"fontdb",
"harfrust",
- "imagesize",
+ "imagesize 0.15.0",
"kurbo",
"log",
"pico-args",
"roxmltree 0.21.1",
"simplecss",
"siphasher",
- "skrifa",
+ "skrifa 0.44.0",
"strict-num",
"svgtypes",
"tiny-skia-path",
@@ -6126,6 +6420,12 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+[[package]]
+name = "weezl"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2"
+
[[package]]
name = "which"
version = "6.0.3"
@@ -6403,6 +6703,19 @@ version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+[[package]]
+name = "write-fonts"
+version = "0.48.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
+dependencies = [
+ "font-types 0.11.3",
+ "indexmap",
+ "kurbo",
+ "log",
+ "read-fonts 0.39.2",
+]
+
[[package]]
name = "writeable"
version = "0.6.4"
@@ -6450,6 +6763,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+[[package]]
+name = "xmp-writer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
+
[[package]]
name = "yasna"
version = "0.5.2"
@@ -6607,3 +6926,18 @@ dependencies = [
"resb",
"serde",
]
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
diff --git a/README.md b/README.md
index 7d7e97a00..c6c8ac7e4 100644
--- a/README.md
+++ b/README.md
@@ -382,7 +382,7 @@ Its current intentional boundaries include:
paint architecture.
- It does not pursue pixel-for-pixel parity with Chrome or provide
high-fidelity Canvas/WebGL/media playback.
-- `--layout` supports software screenshots and raster-backed CDP PDF
+- `--layout` supports software screenshots and native CDP/CLI PDF with embedded fonts
generation, but not every Chrome screenshot or print mode is implemented.
Unsupported protocol paths return explicit errors — Moli never pretends that a
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/pdf.py b/moli-cdp-smoke/moli_cdp_smoke/groups/pdf.py
index 702078cbb..3f42af166 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/pdf.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/pdf.py
@@ -102,6 +102,9 @@ async def _open_fixture_target(client: RawCdpClient, fixture: str) -> tuple[str,
(() => {
document.documentElement.style.cssText = 'margin:0;background:white';
document.body.style.cssText = 'margin:0;min-height:1800px;background:#123456';
+ document.body.innerHTML = [20, 820, 1620].map((top, i) =>
+ `<p style="position:absolute;top:${top}px;margin:0">Font Text 123 page ${i + 1}</p>`
+ ).join('');
const style = document.createElement('style');
style.textContent = '@media print { body { background: #234567 } }';
document.head.append(style);
@@ -250,12 +253,15 @@ async def run_pdf_group(
((432.0, 288.0),),
"landscape PDF MediaBox",
)
+ assert_equal(base64_info.page_text, ("Font Text 123 page 1", "Font Text 123 page 2"), "selected PDF text")
+ assert_equal(stream_info.page_text, ("Font Text 123 page 1", "Font Text 123 page 2", "Font Text 123 page 3"), "stream PDF text")
detail.update(
{
"selectedPages": base64_info.page_count,
"allPages": stream_info.page_count,
"landscapeMediaBox": list(landscape_info.media_boxes[0]),
- "xrefValidated": True,
+ "structureValidated": True,
+ "textExtractionValidated": True,
}
)
record(results, "page_print_to_pdf", detail)
diff --git a/moli-cdp-smoke/moli_cdp_smoke/pdf_document.py b/moli-cdp-smoke/moli_cdp_smoke/pdf_document.py
index dddf8b2f5..82d6a8da3 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/pdf_document.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/pdf_document.py
@@ -1,7 +1,9 @@
from __future__ import annotations
-import re
from dataclasses import dataclass
+from io import BytesIO
+
+from pypdf import PdfReader
from .assertions import SmokeError
@@ -10,7 +12,7 @@ from .assertions import SmokeError
class MoliPdfInfo:
page_count: int
media_boxes: tuple[tuple[float, float], ...]
- xref_offset: int
+ page_text: tuple[str, ...]
def assert_pdf_envelope(data: bytes, label: str) -> None:
@@ -21,33 +23,53 @@ def assert_pdf_envelope(data: bytes, label: str) -> None:
def inspect_moli_pdf(data: bytes, label: str) -> MoliPdfInfo:
+ """Inspect actual PDF objects, including compressed objects and Form resources."""
assert_pdf_envelope(data, label)
- if b"\xff\xd8" not in data or b"\xff\xd9" not in data:
- raise SmokeError(f"{label} did not contain the rendered JPEG payload")
- startxref = re.search(rb"startxref\s+(\d+)\s+%%EOF\s*$", data)
- if startxref is None:
- raise SmokeError(f"{label} did not contain a terminal startxref offset")
- xref_offset = int(startxref.group(1))
- if data[xref_offset : xref_offset + 4] != b"xref":
- raise SmokeError(f"{label} startxref did not point at the xref table")
-
- pages = re.search(rb"/Type /Pages /Kids \[[^]]*] /Count (\d+)", data)
- if pages is None:
- raise SmokeError(f"{label} did not contain the Moli Pages tree")
- page_count = int(pages.group(1))
- media_boxes = tuple(
- (float(width), float(height))
- for width, height in re.findall(
- rb"/MediaBox \[0 0 ([0-9.]+) ([0-9.]+)]",
- data,
- )
- )
- if len(media_boxes) != page_count:
- raise SmokeError(
- f"{label} Pages count/media boxes disagree: {page_count} vs {media_boxes!r}"
+ try:
+ reader = PdfReader(BytesIO(data), strict=True)
+ fonts = []
+ visited = set()
+
+ def resolve(value):
+ return value.get_object() if hasattr(value, "get_object") else value
+
+ def inspect_resources(resources):
+ resources = resolve(resources)
+ if id(resources) in visited:
+ return
+ visited.add(id(resources))
+ for ref in resolve(resources.get("/Font", {})).values():
+ font = ref.get_object()
+ if "/ToUnicode" not in font or not font["/ToUnicode"].get_data():
+ raise SmokeError(f"{label} has text without a Unicode mapping")
+ faces = font.get("/DescendantFonts", [font])
+ for face in faces:
+ descriptor = face.get_object().get("/FontDescriptor")
+ if descriptor is None or not any(
+ key in descriptor.get_object()
+ and descriptor.get_object()[key].get_data()
+ for key in ("/FontFile", "/FontFile2", "/FontFile3")
+ ):
+ raise SmokeError(f"{label} has a font without embedded data")
+ fonts.append(font)
+ for ref in resolve(resources.get("/XObject", {})).values():
+ obj = ref.get_object()
+ if "/Resources" in obj:
+ inspect_resources(obj["/Resources"])
+
+ for page in reader.pages:
+ inspect_resources(page.get("/Resources", {}))
+ if not fonts:
+ raise SmokeError(f"{label} did not contain embedded text fonts")
+ return MoliPdfInfo(
+ page_count=len(reader.pages),
+ media_boxes=tuple(
+ (float(page.mediabox.width), float(page.mediabox.height))
+ for page in reader.pages
+ ),
+ page_text=tuple(" ".join(page.extract_text().split()) for page in reader.pages),
)
- return MoliPdfInfo(
- page_count=page_count,
- media_boxes=media_boxes,
- xref_offset=xref_offset,
- )
+ except SmokeError:
+ raise
+ except Exception as error:
+ raise SmokeError(f"{label} was not a readable PDF: {error}") from error
diff --git a/moli-cdp-smoke/pyproject.toml b/moli-cdp-smoke/pyproject.toml
index 75c21d46b..6ad3db772 100644
--- a/moli-cdp-smoke/pyproject.toml
+++ b/moli-cdp-smoke/pyproject.toml
@@ -6,6 +6,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"
requires-python = ">=3.11"
dependencies = [
+ "pypdf>=6,<7",
"playwright>=1.48,<2",
"websockets>=13,<16",
]
diff --git a/moli-cdp-smoke/uv.lock b/moli-cdp-smoke/uv.lock
index 21f7e1739..455e6c831 100644
--- a/moli-cdp-smoke/uv.lock
+++ b/moli-cdp-smoke/uv.lock
@@ -65,12 +65,14 @@ version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "playwright" },
+ { name = "pypdf" },
{ name = "websockets" },
]
[package.metadata]
requires-dist = [
{ name = "playwright", specifier = ">=1.48,<2" },
+ { name = "pypdf", specifier = ">=6,<7" },
{ name = "websockets", specifier = ">=13,<16" },
]
@@ -105,6 +107,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/c4/b4d4827c93ef43c01f599ef31453ccc1c132b353284fc6c87d535c233129/pyee-13.0.1-py3-none-any.whl", hash = "sha256:af2f8fede4171ef667dfded53f96e2ed0d6e6bd7ee3bb46437f77e3b57689228", size = 15659, upload-time = "2026-02-14T21:12:26.263Z" },
]
+[[package]]
+name = "pypdf"
+version = "6.20.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/45/7e/d08c72b29e89b1ad14acaae817685ca06bac93691bddfd4fac08a703e5b0/pypdf-6.20.0.tar.gz", hash = "sha256:72b1e897fef7f5bbed7f2a93881a4861d98dbf25ae39981c8a023583239edbda", size = 7072602, upload-time = "2026-10-09T10:49:39.165Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/42/a945f65cc61c739ec80f4112c4b78ed1791f25d33f45f19389c9c9e247e2/pypdf-6.20.0-py3-none-any.whl", hash = "sha256:f003fc2014814d264fe7dd3f9d435c158e23e1a85a2233f87a0a2d6d21c914ad", size = 401710, upload-time = "2026-10-09T10:49:36.882Z" },
+]
+
[[package]]
name = "typing-extensions"
version = "4.15.0"
diff --git a/moli-core/src/page/command_dispatch.rs b/moli-core/src/page/command_dispatch.rs
index 65efcc600..c1b6e4903 100644
--- a/moli-core/src/page/command_dispatch.rs
+++ b/moli-core/src/page/command_dispatch.rs
@@ -402,6 +402,7 @@ impl Page {
RendererPageReply::PageDiagnosticsSnapshot(_) => "a page diagnostics snapshot reply",
RendererPageReply::CookieFacadeSnapshot(_) => "a cookie facade snapshot reply",
RendererPageReply::LayoutMetrics(_) => "a layout metrics reply",
+ RendererPageReply::PrintToPdf(_) => "a print to PDF reply",
RendererPageReply::CaptureScreenshot(_) => "a capture screenshot reply",
RendererPageReply::CaptureScreencastFrame(_) => "a capture screencast frame reply",
RendererPageReply::Unit => "a unit reply",
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index 2c1bcb093..af8576c9f 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -114,30 +114,30 @@ pub use moli_renderer_v8::{
RendererPageCommandPostResponseContinuation, RendererPageCreationArtifacts,
RendererPageCreationDiagnostics, RendererPageDiagnosticsSnapshot, RendererPageDumpFormat,
RendererPageDumpOptions, RendererPageDumpStripOptions, RendererPageReplacementError,
- RendererPageReplacementFailureDisposition, RendererPendingAuxiliaryPage,
+ RendererPageReplacementFailureDisposition, RendererPdfOptions, RendererPendingAuxiliaryPage,
RendererPendingDownloadActivation, RendererPendingDownloadResponse,
RendererPendingFileChooserActivation, RendererPendingJavaScriptDialog,
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererPerformanceMetricSnapshot, RendererPointerEventProperties,
- RendererPopupActivationSource, RendererPopupDisposition, RendererResourceContentBody,
- RendererResourceSearchRequest, RendererResourceTextSearchOutcome, RendererRuntimeCommandOutput,
- RendererRuntimeHeapUsage, RendererRuntimeInspectorIoCommandClaim,
- RendererRuntimeInspectorIoCommandRoute, RendererRuntimeInspectorMainCommandCompletion,
- RendererRuntimeInspectorMainCommandRoute, RendererRuntimeInspectorMessage,
- RendererRuntimeInspectorMessageBatch, RendererRuntimeInspectorProtocolMessage,
- RendererRuntimeInspectorProtocolMessageValueMut, RendererRuntimeObservableSourceItem,
- RendererRuntimeObservableSourceSummary, RendererRuntimeRealmInfo, RendererScreenshotClip,
- RendererScreenshotFormat, RendererScreenshotPurpose, RendererScreenshotRegion,
- RendererScrollIntoViewResult, RendererServiceWorkerConsoleMessage,
- RendererServiceWorkerExceptionMessage, RendererServiceWorkerFetchDiagnostic,
- RendererServiceWorkerFetchDiagnosticResult, RendererServiceWorkerRunIdentity,
- RendererServiceWorkerTargetEvent, RendererServiceWorkerTargetInfo,
- RendererServiceWorkerVersionStatus, RendererSetDocumentContentResult,
- RendererSharedWorkerConsoleMessage, RendererSharedWorkerTargetEvent,
- RendererSharedWorkerTargetInfo, RendererSyntheticResponseBody, RendererTextSearchMatch,
- RendererTouchPoint, RendererVisualStateToken, RendererWindowDocumentSource,
- RuntimeConsoleMessageSnapshot,
+ RendererPopupActivationSource, RendererPopupDisposition, RendererPrintToPdfReply,
+ RendererPrintToPdfRequest, RendererResourceContentBody, RendererResourceSearchRequest,
+ RendererResourceTextSearchOutcome, RendererRuntimeCommandOutput, RendererRuntimeHeapUsage,
+ RendererRuntimeInspectorIoCommandClaim, RendererRuntimeInspectorIoCommandRoute,
+ RendererRuntimeInspectorMainCommandCompletion, RendererRuntimeInspectorMainCommandRoute,
+ RendererRuntimeInspectorMessage, RendererRuntimeInspectorMessageBatch,
+ RendererRuntimeInspectorProtocolMessage, RendererRuntimeInspectorProtocolMessageValueMut,
+ RendererRuntimeObservableSourceItem, RendererRuntimeObservableSourceSummary,
+ RendererRuntimeRealmInfo, RendererScreenshotClip, RendererScreenshotFormat,
+ RendererScreenshotPurpose, RendererScreenshotRegion, RendererScrollIntoViewResult,
+ RendererServiceWorkerConsoleMessage, RendererServiceWorkerExceptionMessage,
+ RendererServiceWorkerFetchDiagnostic, RendererServiceWorkerFetchDiagnosticResult,
+ RendererServiceWorkerRunIdentity, RendererServiceWorkerTargetEvent,
+ RendererServiceWorkerTargetInfo, RendererServiceWorkerVersionStatus,
+ RendererSetDocumentContentResult, RendererSharedWorkerConsoleMessage,
+ RendererSharedWorkerTargetEvent, RendererSharedWorkerTargetInfo, RendererSyntheticResponseBody,
+ RendererTextSearchMatch, RendererTouchPoint, RendererVisualStateToken,
+ RendererWindowDocumentSource, RuntimeConsoleMessageSnapshot,
};
pub use moli_renderer_v8::{
RendererAppManifest, RendererAppManifestDisplayMode, RendererAppManifestError,
diff --git a/moli-core/src/page/renderer_command_support.rs b/moli-core/src/page/renderer_command_support.rs
index 7d34e2c12..9fb47a84c 100644
--- a/moli-core/src/page/renderer_command_support.rs
+++ b/moli-core/src/page/renderer_command_support.rs
@@ -1689,6 +1689,30 @@ impl Page {
)
}
+ pub fn start_print_to_pdf(
+ &self,
+ request: super::RendererPrintToPdfRequest,
+ ) -> Result<PendingPageCommand> {
+ self.start_page_command(RendererPageCommand::PrintToPdf(request))
+ }
+
+ pub fn finish_print_to_pdf(
+ &mut self,
+ completion: CompletedPageCommand,
+ ) -> Result<super::RendererPrintToPdfReply> {
+ anyhow::ensure!(
+ completion.renderer_agent_attachment_id() == self.renderer_agent_attachment_id(),
+ "print to PDF completed for a stale renderer attachment"
+ );
+ let reply = self.finish_page_command(completion);
+ expect_page_reply!(
+ reply,
+ "print to PDF page command",
+ "a print to PDF reply",
+ RendererPageReply::PrintToPdf(result) => Ok(result),
+ )
+ }
+
pub fn start_capture_screenshot(&self) -> Result<PendingPageCommand> {
self.start_capture_screenshot_with_request(RendererCaptureScreenshotRequest::viewport_png())
}
diff --git a/moli-layout/src/capture.rs b/moli-layout/src/capture.rs
index d1db5ce79..03a8aece1 100644
--- a/moli-layout/src/capture.rs
+++ b/moli-layout/src/capture.rs
@@ -16,6 +16,9 @@ pub enum PaintCaptureRegion {
Viewport,
/// The complete document content extent computed by this layout pass.
FullDocument,
+ /// The complete document for vector printing. The PDF backend applies
+ /// page/work budgets instead of the full-document bitmap dimension limit.
+ PrintDocument,
/// One explicit page-coordinate rectangle.
PageClip { rect: LayoutRect, scale: f32 },
/// Present the existing viewport on a separate raster surface. Scroll
@@ -89,6 +92,14 @@ impl PaintCaptureRequest {
}
}
+ /// Captures vector print content without imposing a full-page pixel buffer.
+ pub const fn print_document() -> Self {
+ Self {
+ region: PaintCaptureRegion::PrintDocument,
+ ..Self::full_document()
+ }
+ }
+
/// Captures one document-coordinate rectangle at the requested clip scale.
pub const fn page_clip(rect: LayoutRect, scale: f32) -> Self {
Self {
@@ -168,8 +179,12 @@ impl PaintCaptureRequest {
PaintCaptureRegion::Viewport | PaintCaptureRegion::TransformedViewport { .. } => {
(viewport_bounds, 1.0)
}
- PaintCaptureRegion::FullDocument => {
- validate_full_document_extent(content_size.width, content_size.height)?;
+ PaintCaptureRegion::FullDocument | PaintCaptureRegion::PrintDocument => {
+ if self.region == PaintCaptureRegion::FullDocument {
+ validate_full_document_extent(content_size.width, content_size.height)?;
+ } else {
+ validate_extent("document content", content_size.width, content_size.height)?;
+ }
(
LayoutRect::new(
-viewport_scroll.x,
@@ -309,6 +324,22 @@ fn invalid_capture(detail: impl Into<String>) -> LayoutError {
mod tests {
use super::*;
+ #[test]
+ fn vector_print_capture_is_not_limited_by_full_page_bitmap_dimensions() {
+ let viewport = LayoutViewport::new(800, 600, 3.0);
+ let size = LayoutSize::new(800.0, 200_000.0);
+ assert!(
+ PaintCaptureRequest::full_document()
+ .resolve(viewport, LayoutPoint::ZERO, size)
+ .is_err()
+ );
+ let print = PaintCaptureRequest::print_document()
+ .resolve(viewport, LayoutPoint::ZERO, size)
+ .unwrap();
+ assert_eq!(print.surface.css_height, size.height);
+ assert!(!print.paint_root_scrollbars);
+ }
+
#[test]
fn full_document_capture_keeps_layout_viewport_and_offsets_scroll() {
let capture = PaintCaptureRequest::full_document()
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 9f5c614a9..27f539359 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -164,6 +164,8 @@ pub(crate) struct InlineStructuralBox {
#[derive(Debug)]
pub(crate) struct InlineFormattingContext {
+ /// The actual whitespace-processed text supplied to the shaper.
+ pub(crate) text: String,
pub(crate) root_style: LayoutBoxId,
/// Reusable Parley layout for intrinsic and final-width probes. Line
/// breaking replaces only Parley's line output while retaining the shaped
@@ -2185,6 +2187,7 @@ impl InlineBuildInput {
.map(|(_, object, _)| object)
.collect();
InlineFormattingContext {
+ text: self.text,
root_style: self.root_style,
measurement_layout: Some(layout),
laid_out: None,
@@ -3352,6 +3355,7 @@ mod tests {
layout.break_all_lines(Some(80.0));
let context = InlineFormattingContext {
+ text: "".into(),
root_style: root,
measurement_layout: Some(layout.clone()),
laid_out: None,
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs
index e3ffb52d1..0a5c67218 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -83,8 +83,8 @@ pub use snapshot::{
PaintImageSampling, PaintLineCap, PaintLineJoin, PaintLinearGradient, PaintPath,
PaintPathElement, PaintPoint, PaintRadialGradient, PaintRect, PaintShape, PaintSize,
PaintSnapshot, PaintStroke, PaintSvgImage, PaintSvgImageId, PaintSvgImageResource,
- PaintTextDecoration, PaintTextDecorationStyle, PaintTextShadow, PaintTransform2D,
- PaintViewport, pixel_snap_paint_axis, pixel_snap_paint_axis_allowing_zero,
+ PaintTextDecoration, PaintTextDecorationStyle, PaintTextSemantics, PaintTextShadow,
+ PaintTransform2D, PaintViewport, pixel_snap_paint_axis, pixel_snap_paint_axis_allowing_zero,
pixel_snap_paint_rect,
};
pub use source::{
diff --git a/moli-layout/src/paint/mod.rs b/moli-layout/src/paint/mod.rs
index 145e0a920..d9a0b0fc7 100644
--- a/moli-layout/src/paint/mod.rs
+++ b/moli-layout/src/paint/mod.rs
@@ -131,6 +131,7 @@ enum UnavailableReplacedContentPaint {
pub(crate) fn project_paint_snapshot<N>(
projection: &OutputProjection<'_, N>,
capture: ResolvedPaintCapture,
+ retain_text_semantics: bool,
embedded_frames: &mut HashMap<LayoutBoxId, PaintSnapshot>,
) -> PaintProjectionResult
where
@@ -143,6 +144,7 @@ where
(capture.base_background_color, None)
};
let mut snapshot = PaintSnapshot::new(projection.viewport, canvas_color);
+ snapshot.retain_text_semantics = retain_text_semantics;
snapshot.surface = capture.surface;
snapshot.viewport_to_surface = capture.viewport_to_surface;
snapshot.content_size = projection.document_content_size();
diff --git a/moli-layout/src/paint/text.rs b/moli-layout/src/paint/text.rs
index c856f4629..913720589 100644
--- a/moli-layout/src/paint/text.rs
+++ b/moli-layout/src/paint/text.rs
@@ -116,7 +116,12 @@ fn project_text_phase<N>(
);
}
+ let text: Option<std::sync::Arc<str>> = (snapshot.retain_text_semantics
+ && phase == TextPaintPhase::Foreground)
+ .then(|| std::sync::Arc::from(context.text.as_str()));
for (line_index, line) in text_layout.lines().enumerate() {
+ let mut mapped_run = None;
+ let mut cluster_ranges = Vec::new().into_iter();
metrics.text_line_count = metrics.text_line_count.saturating_add(1);
let line_is_culled =
local_cull.is_some_and(|cull| {
@@ -146,6 +151,21 @@ fn project_text_phase<N>(
PositionedLayoutItem::InlineBox(_) => continue,
PositionedLayoutItem::GlyphRun(glyph_run) => glyph_run,
};
+ let run = glyph_run.run();
+ if text.is_some() && mapped_run != Some(run.index()) {
+ cluster_ranges = glyph_cluster_ranges(run).into_iter();
+ mapped_run = Some(run.index());
+ }
+ // Advance even for masked/hidden style runs, so styled portions of
+ // the same Parley run keep their original cluster associations.
+ let clusters = cluster_ranges
+ .by_ref()
+ .take(if text.is_some() {
+ glyph_run.glyphs().count()
+ } else {
+ 0
+ })
+ .collect();
if let Some(TextClipMaskScope::InlineBox(target)) = mask_scope
&& !context.style_is_within_box(usize::from(glyph_run.style_index()), target)
{
@@ -154,7 +174,6 @@ fn project_text_phase<N>(
if !glyph_run.style().brush.paint {
continue;
}
- let run = glyph_run.run();
let vertical_offset = line_placement
.map(|placement| placement.item_offset(item_index))
.unwrap_or_default();
@@ -198,6 +217,10 @@ fn project_text_phase<N>(
glyph_skew_radians: synthesis.skew().map(f32::to_radians),
glyph_embolden,
glyphs,
+ text: text.as_ref().map(|text| crate::PaintTextSemantics {
+ text: text.clone(),
+ clusters,
+ }),
transform,
};
let brush = &glyph_run.style().brush;
@@ -267,6 +290,30 @@ fn project_text_phase<N>(
}
}
+fn glyph_cluster_ranges(
+ run: &parley::Run<'_, crate::stylo_to_parley::TextBrush>,
+) -> Vec<std::ops::Range<usize>> {
+ // Join ligature continuations in logical order first: in RTL their
+ // visual order puts the continuation *before* the glyph-bearing cluster.
+ let mut atoms: Vec<(std::ops::Range<usize>, usize)> = Vec::new();
+ for cluster in run.clusters() {
+ if cluster.is_ligature_continuation() {
+ if let Some((range, _)) = atoms.last_mut() {
+ range.end = cluster.text_range().end;
+ }
+ } else {
+ atoms.push((cluster.text_range(), cluster.glyphs().count()));
+ }
+ }
+ if run.is_rtl() {
+ atoms.reverse();
+ }
+ atoms
+ .into_iter()
+ .flat_map(|(range, count)| std::iter::repeat_n(range, count))
+ .collect()
+}
+
fn project_selection(
context: &InlineFormattingContext,
text_layout: &parley::Layout<crate::stylo_to_parley::TextBrush>,
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index b2022c72e..a5244c87c 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -69,7 +69,12 @@ where
request
.resolve(viewport, projection.viewport_scroll, content_size)
.map(|capture| {
- crate::paint::project_paint_snapshot(&projection, capture, &mut embedded_paint)
+ crate::paint::project_paint_snapshot(
+ &projection,
+ capture,
+ reason == LayoutFlushReason::Print,
+ &mut embedded_paint,
+ )
})
})
.transpose()?
diff --git a/moli-layout/src/snapshot.rs b/moli-layout/src/snapshot.rs
index f4fc1f950..80c99641e 100644
--- a/moli-layout/src/snapshot.rs
+++ b/moli-layout/src/snapshot.rs
@@ -636,10 +636,21 @@ pub struct PaintGlyphRun {
pub glyph_embolden: PaintPoint,
/// Fully positioned glyphs.
pub glyphs: Vec<PaintGlyph>,
+ /// Logical text and UTF-8 cluster ranges, shared with other runs in this paragraph.
+ /// Masks and other purely visual glyphs have no text semantics.
+ pub text: Option<PaintTextSemantics>,
/// Maps the glyph positions from their layout coordinate space to viewport CSS pixels.
pub transform: PaintTransform2D,
}
+/// Owned text mapping retained across the layout/paint boundary for document export.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PaintTextSemantics {
+ pub text: std::sync::Arc<str>,
+ /// One range per positioned glyph; a cluster may cover several glyphs or characters.
+ pub clusters: Vec<std::ops::Range<usize>>,
+}
+
/// CSS line style for an owned text-decoration command.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PaintTextDecorationStyle {
@@ -876,6 +887,8 @@ impl PaintDiagnostic {
/// representation before returning.
#[derive(Clone, Debug, PartialEq)]
pub struct PaintSnapshot {
+ /// Print projections retain Unicode mappings; raster-only captures omit them.
+ pub(crate) retain_text_semantics: bool,
/// Live CSS layout viewport used to build this snapshot.
pub viewport: PaintViewport,
/// Short-lived raster surface selected for this capture.
@@ -905,6 +918,7 @@ impl PaintSnapshot {
/// Creates an empty snapshot for a viewport and canvas color.
pub fn new(viewport: PaintViewport, canvas_color: PaintColor) -> Self {
Self {
+ retain_text_semantics: false,
viewport,
surface: PaintCaptureSurface::for_viewport(viewport),
viewport_to_surface: PaintTransform2D::IDENTITY,
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rs
index 1bb3850ea..dc1a1ca28 100644
--- a/moli-layout/src/taffy_tree.rs
+++ b/moli-layout/src/taffy_tree.rs
@@ -3115,6 +3115,7 @@ pub(crate) fn single_subject_block_alignment_offset(
fn empty_inline_context() -> InlineFormattingContext {
InlineFormattingContext {
+ text: "".into(),
root_style: LayoutBoxId::from_index(0),
measurement_layout: Some(parley::Layout::default()),
laid_out: None,
diff --git a/moli-paint/Cargo.toml b/moli-paint/Cargo.toml
index 858d4044a..988dee2bd 100644
--- a/moli-paint/Cargo.toml
+++ b/moli-paint/Cargo.toml
@@ -5,6 +5,8 @@ edition = "2024"
license = "MIT OR Apache-2.0"
[dependencies]
+krilla = { git = "https://github.com/LaurenzV/krilla", rev = "5eb4e1fb24a24ce78b533c23b080969917530c32", default-features = false, features = ["raster-images"] }
+skrifa = "0.44.0"
anyrender = { git = "https://github.com/ldm0/anyrender", rev = "18fd67d7a5622a9821d86434857fd69856912a43" }
anyrender_svg = { git = "https://github.com/ldm0/anyrender", rev = "18fd67d7a5622a9821d86434857fd69856912a43", default-features = false, features = ["text"] }
anyrender_vello_cpu = { git = "https://github.com/ldm0/anyrender", rev = "18fd67d7a5622a9821d86434857fd69856912a43", default-features = false, features = ["bitmap-glyphs", "filters"] }
@@ -12,5 +14,8 @@ moli-image = { path = "../moli-image" }
moli-layout = { path = "../moli-layout" }
peniko = "0.6.0"
+[dev-dependencies]
+lopdf = { version = "0.45.0", default-features = false }
+
[lints]
workspace = true
diff --git a/moli-paint/README.md b/moli-paint/README.md
new file mode 100644
index 000000000..b1d9cb868
--- /dev/null
+++ b/moli-paint/README.md
@@ -0,0 +1,135 @@
+# Paint backends
+
+`raster_snapshot` produces RGBA pixels through AnyRender/Vello CPU.
+`pdf::pdf_snapshot` consumes the same owned snapshot and writes PDF through
+upstream [Krilla at `5eb4e1f`](https://github.com/LaurenzV/krilla/commit/5eb4e1fb24a24ce78b533c23b080969917530c32).
+CDP `Page.printToPDF` and CLI `--dump pdf` use the PDF backend.
+The renderer owns the print request, restores media after snapshot capture, and
+returns PDF bytes to both clients without publishing interactive geometry. Vector
+print capture is independent of the full-document bitmap dimension limit.
+
+The dependency uses a fixed Git revision with only `raster-images` enabled;
+`simple-text` remains disabled because Parley already performs shaping. Krilla's
+own `pdf-writer` Git pin (`fdf0901`) is recorded in `Cargo.lock`. This revision
+requires Rust 1.92; the repository toolchain is 1.96.1. Krilla and the adapter now
+share `skrifa` 0.44 with Parley, Vello and usvg. The adapter uses `skrifa::raw`
+instead of declaring a separate `read-fonts` dependency. The `subsetter` 0.2.6
+dependency still brings `skrifa` 0.42, `read-fonts` 0.39 and `font-types` 0.11:
+its upstream `main` also requires those versions, so switching Krilla to Git
+does not remove that older stack. Krilla's `imagesize` 0.14 and `base64` 0.22
+also coexist with usvg's 0.15 and 0.23; their version requirements do not overlap.
+
+The PDF adapter embeds and subsets fonts, using Parley's existing glyph positions
+and the snapshot's shared logical text/UTF-8 cluster ranges. These mappings are
+collected only for print demands, keeping them out of the screenshot hot path.
+Ligature ranges are joined in logical order before arranging RTL clusters visually. Synthetic italic
+uses a glyph-local shear; synthetic weight uses PDF fill-and-stroke. Font instances
+are cached separately by font identity and normalized variation coordinates.
+The adapter reverses `avar` v1 and `fvar` normalization for Krilla's design-space
+variation API. Non-default `avar` v2 instances currently return an explicit error.
+
+Paths, borders, decorations, basic SVG paths, images, sRGB linear and non-repeating
+radial gradients, clips, opacity and PDF blend modes use native PDF primitives.
+Existing AnyRender geometry lowering is shared for non-text drawing; text bypasses
+its glyph API because that API does not carry Unicode semantics. SVG scenes that
+cannot be replayed natively, shadows, other gradient interpolation spaces and
+filters use bounded CPU raster fallbacks. Ordinary filtered text gets one transparent
+text copy for extraction, subject to page ownership, clips and opacity. Fully
+transparent groups contribute no text. Curved/rotated clips use a bounded CPU
+coverage probe at two samples per CSS pixel to exclude invisible clusters; the
+actual glyphs remain native PDF text. Destination masks that leave some visible
+ink and contain body text currently return an explicit error: their per-cluster
+semantic visibility is not inferred from the result image's bounding box.
+Destination-dependent operators (including `plus-lighter`) also require a
+containing isolated layer. Shadow and clip-mask glyphs never add semantic copies.
+When visible lettering comes only from `background-clip:text` with a transparent
+foreground, it is rasterized mask artwork and is not searchable in this version.
+
+`krilla-svg` was evaluated but not added: both its compatible release and the
+pinned upstream Git revision use usvg 0.47, while Moli owns usvg 0.48 trees.
+Basic SVG geometry reuses the existing AnyRender lowering; more complex SVGs
+use a bounded image fallback.
+
+Pagination retains the previous fit-to-printable-width behavior and slices the
+continuous print layout. Each text cluster is assigned by the center of its visible, transformed ink
+bounds after document clipping. It has one semantic owner page; ink that
+crosses onto a neighboring page is outlined there. This prevents off-page runs and
+replayed slices from duplicating the extracted document. Device pixel ratio does
+not affect PDF page geometry. Page ranges still refer to original document pages.
+
+This does not implement CSS fragmentation (`break-inside`, repeated table headers,
+`@page`), tagged PDF, link annotations or document outlines. PDF reading order still
+follows paint order, and complex-script extraction depends on the reader's handling
+of ToUnicode/ActualText. SVG text that takes a raster fallback has no separate text
+mapping. This is not an accessibility or PDF/UA implementation. Krilla
+uses ActualText for ambiguous/multiple-glyph clusters and Type3 fonts for some
+color glyphs. A reader that ignores these can report incorrect text even when
+MuPDF/Poppler extract it correctly; track upstream issues [411](https://github.com/LaurenzV/krilla/issues/411)
+and [425](https://github.com/LaurenzV/krilla/issues/425). In the generated shaping
+sample, PDF.js 5.6.205 reproduces incorrect extraction of ordinary `a` after the
+same glyph was mapped to the `a` + combining acute cluster. MuPDF 1.28.2 and
+Poppler 25.03.0 extract those strings correctly. These results were rechecked
+with the pinned Git revision. This is an observed compatibility
+limit, not a claim of cross-reader complex-text conformance. Apple Preview and
+interactive browser selection/copy still require manual checks.
+
+Run the PDF regressions with:
+
+```sh
+cargo nextest run -p moli-paint -E 'test(pdf::)'
+cargo nextest run -p moli-protocol -E 'test(print_to_pdf) | test(domains::page::pdf::)'
+```
+
+`tests/fixtures/moli-pdf.ttf` is original MIT/Apache-2.0 test data derived from the
+repository's generated Ahem face. It adds `fi`/`ffi` ligatures and a `wght` axis with
+a non-linear `avar` map, combining-mark positioning, Hebrew coverage and COLR
+color glyphs. Regenerate it with
+`uv run scripts/generate-pdf-test-font.py` from the repository root.
+
+Reader-level regression and artifact generation:
+
+```sh
+uv run scripts/check-native-pdf.py --moli target/debug/moli
+cd moli-cdp-smoke
+uv run moli-cdp-smoke --group pdf
+```
+
+The reader script checks the real CLI with MuPDF, including mixed RTL, multi-glyph
+clusters, repeated base letters, color glyphs, opacity, shadows, filters and a
+200,100 CSS-pixel document. It retains PDFs, rendered pages, extracted text and
+per-process timings/sampled peak RSS in `target/native-pdf-check/`. The Rust tests
+use lopdf for PDF objects and ordinary text; its extractor does not interpret
+ActualText and Type3 text correctly, so it is not the complex-text oracle.
+
+Validation on 2026-10-12 (Linux x86_64, Rust 1.96.1): `cargo fmt --all`,
+workspace Clippy with all targets/features and warnings denied, and the full
+nextest run passed (20,011 tests; 17 skipped). The Python smoke unit suite passed
+43 tests. The real PDF smoke group passed with both debug and release binaries.
+The visual comparison covered borders, rounded clips, an sRGB gradient, alpha
+image, SVG paths, transformed text, opacity, shadow and blur. Interior gradient
+samples differed by at most one 8-bit channel value from the raster screenshot.
+The Git revision also passed the real CLI/MuPDF checks and CDP PDF smoke group;
+its rendered visual sample was pixel-identical to the crates.io baseline.
+
+The release measurements below were taken with crates.io Krilla 0.8.2 before
+the Git switch; they have not been remeasured for the pinned revision.
+The repository release profile produced a 158,402,744-byte binary (151.06 MiB,
+not stripped by the profile). Compared with the previous lockfile, the production
+paint dependency closure adds 11 crate versions, plus a bitflags upgrade required
+by the test parser. A same-revision baseline binary was not built, so these
+measurements do not establish the PDF backend's binary-size delta.
+
+One observed release CLI run with local data URLs and fixed fonts:
+
+| Input | Pages | PDF bytes | Whole CLI time | Sampled process peak RSS |
+| --- | ---: | ---: | ---: | ---: |
+| Font Text 123 | 1 | 3,290 | 95 ms | 53.3 MiB |
+| Shaping / font variants | 1 | 9,119 | 32 ms | 52.9 MiB |
+| Opacity / shadow / blur | 1 | 7,070 | 52 ms | 56.1 MiB |
+| 286 rows, 200,100 CSS px | 79 | 45,215 | 144 ms | 59.3 MiB |
+
+These include process startup, font loading, layout and encoding. RSS is sampled
+from `/proc` every 5 ms, not an allocator-level peak; timings are observations,
+not a performance guarantee. The long document contained no Image XObjects, and
+all 286 row labels were extracted once. The effects sample contained two local
+raster images, with one semantic copy of each visible text run.
diff --git a/moli-paint/src/lib.rs b/moli-paint/src/lib.rs
index 458719228..afe452290 100644
--- a/moli-paint/src/lib.rs
+++ b/moli-paint/src/lib.rs
@@ -1,4 +1,4 @@
-//! CPU rasterization for owned Moli paint snapshots.
+//! PDF output and CPU rasterization for owned Moli paint snapshots.
//!
//! The implementation is intentionally a narrow adaptation of the AnyRender
//! screenshot path used by Blitz at commit
@@ -6,6 +6,7 @@
//! AnyRender code is licensed under MIT OR Apache-2.0. No Blitz DOM or retained
//! layout state is copied into this crate.
+pub mod pdf;
mod raster;
pub use moli_image::RgbaImage as RasterImage;
diff --git a/moli-paint/src/pdf/image.rs b/moli-paint/src/pdf/image.rs
new file mode 100644
index 000000000..7cbf3f86e
--- /dev/null
+++ b/moli-paint/src/pdf/image.rs
@@ -0,0 +1,58 @@
+use std::sync::Arc;
+
+use krilla::image::{BitsPerComponent, CustomImage, Image, ImageColorspace};
+
+use super::PdfError;
+
+#[derive(Clone, Hash)]
+struct ImageChannels {
+ rgb: Arc<[u8]>,
+ alpha: Arc<[u8]>,
+ width: u32,
+ height: u32,
+}
+impl CustomImage for ImageChannels {
+ fn color_channel(&self) -> &[u8] {
+ &self.rgb
+ }
+ fn alpha_channel(&self) -> Option<&[u8]> {
+ Some(&self.alpha)
+ }
+ fn bits_per_component(&self) -> BitsPerComponent {
+ BitsPerComponent::Eight
+ }
+ fn size(&self) -> (u32, u32) {
+ (self.width, self.height)
+ }
+ fn icc_profile(&self) -> Option<&[u8]> {
+ None
+ }
+ fn color_space(&self) -> ImageColorspace {
+ ImageColorspace::Rgb
+ }
+}
+
+pub(super) fn from_rgba(image: &crate::RasterImage, interpolate: bool) -> Result<Image, PdfError> {
+ let expected = (image.width as usize)
+ .checked_mul(image.height as usize)
+ .and_then(|size| size.checked_mul(4));
+ if image.width == 0 || image.height == 0 || expected != Some(image.rgba.len()) {
+ return Err(PdfError::Encoding("invalid RGBA image resource".into()));
+ }
+ let mut rgb = Vec::with_capacity(image.rgba.len() / 4 * 3);
+ let mut alpha = Vec::with_capacity(image.rgba.len() / 4);
+ for pixel in image.rgba.as_chunks::<4>().0 {
+ rgb.extend_from_slice(&pixel[..3]);
+ alpha.push(pixel[3]);
+ }
+ Image::from_custom(
+ ImageChannels {
+ rgb: rgb.into(),
+ alpha: alpha.into(),
+ width: image.width,
+ height: image.height,
+ },
+ interpolate,
+ )
+ .map_err(PdfError::Encoding)
+}
diff --git a/moli-paint/src/pdf/mod.rs b/moli-paint/src/pdf/mod.rs
new file mode 100644
index 000000000..484417d08
--- /dev/null
+++ b/moli-paint/src/pdf/mod.rs
@@ -0,0 +1,196 @@
+//! Native PDF output from owned paint snapshots. Layout and shaping remain in Moli.
+//!
+//! PDF pages are slices of the existing continuous print layout. Unsupported
+//! effects are rasterized at their own clipped bounds; ordinary text stays text.
+
+mod image;
+mod primitives;
+mod text;
+mod validation;
+
+use std::{collections::BTreeSet, fmt, ops::RangeInclusive};
+
+use krilla::{Document, geom::Size, page::PageSettings};
+use moli_layout::{PaintRect, PaintSnapshot};
+use peniko::kurbo::{Affine, Rect};
+
+use primitives::PdfPainter;
+
+/// Page geometry in PDF points (72 per inch). Ranges are zero-based and inclusive.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PdfOptions {
+ pub width: f64,
+ pub height: f64,
+ pub margin_top: f64,
+ pub margin_bottom: f64,
+ pub margin_left: f64,
+ pub margin_right: f64,
+ pub scale: f64,
+ pub page_ranges: Vec<RangeInclusive<usize>>,
+}
+
+impl Default for PdfOptions {
+ fn default() -> Self {
+ Self {
+ width: 612.0,
+ height: 792.0,
+ margin_top: 72.0 / 2.54,
+ margin_bottom: 72.0 / 2.54,
+ margin_left: 72.0 / 2.54,
+ margin_right: 72.0 / 2.54,
+ scale: 1.0,
+ page_ranges: Vec::new(),
+ }
+ }
+}
+
+#[derive(Debug)]
+pub enum PdfError {
+ InvalidParameters,
+ PageRangeExceeded,
+ ResourceLimit,
+ Paint(crate::PaintError),
+ Encoding(String),
+}
+
+impl fmt::Display for PdfError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::InvalidParameters => f.write_str("invalid print parameters"),
+ Self::PageRangeExceeded => f.write_str("Page range exceeds page count"),
+ Self::ResourceLimit => f.write_str("Printing failed: PDF work budget exceeded"),
+ Self::Paint(error) => error.fmt(f),
+ Self::Encoding(message) => write!(f, "Printing failed: {message}"),
+ }
+ }
+}
+impl std::error::Error for PdfError {}
+impl From<crate::PaintError> for PdfError {
+ fn from(error: crate::PaintError) -> Self {
+ Self::Paint(error)
+ }
+}
+
+/// Writes embedded, subsetted fonts and native drawing commands. Device pixel
+/// ratio does not affect page geometry. This does not perform CSS fragmentation.
+pub fn pdf_snapshot(snapshot: &PaintSnapshot, options: &PdfOptions) -> Result<Vec<u8>, PdfError> {
+ let metrics = crate::raster::validate_fragment_stream(snapshot)?;
+ validation::validate(snapshot)?;
+ let width = f64::from(snapshot.surface.css_width);
+ let height = f64::from(snapshot.surface.css_height);
+ let printable_width = options.width - options.margin_left - options.margin_right;
+ let printable_height = options.height - options.margin_top - options.margin_bottom;
+ if [
+ width,
+ height,
+ options.width,
+ options.height,
+ printable_width,
+ printable_height,
+ options.scale,
+ ]
+ .iter()
+ .any(|value| !value.is_finite() || *value <= 0.0)
+ || [
+ options.margin_top,
+ options.margin_bottom,
+ options.margin_left,
+ options.margin_right,
+ ]
+ .iter()
+ .any(|value| !value.is_finite() || *value < 0.0)
+ || options.width > 14_400.0
+ || options.height > 14_400.0
+ || !(0.1..=2.0).contains(&options.scale)
+ {
+ return Err(PdfError::InvalidParameters);
+ }
+ // Preserve the existing shrink-to-printable-width contract.
+ let scale = printable_width * options.scale / width;
+ let page_height = printable_height / scale;
+ let page_count = (height / page_height).ceil().max(1.0);
+ if !page_count.is_finite() || page_count > 100_000.0 {
+ return Err(PdfError::ResourceLimit);
+ }
+ let page_count = page_count as usize;
+ let selected: BTreeSet<usize> = if options.page_ranges.is_empty() {
+ (0..page_count).collect()
+ } else {
+ options
+ .page_ranges
+ .iter()
+ .flat_map(|range| *range.start()..=(*range.end()).min(page_count - 1))
+ .collect()
+ };
+ if selected.is_empty() {
+ return Err(PdfError::PageRangeExceeded);
+ }
+ if selected.len().saturating_mul(metrics.operation_count) > 20_000_000 {
+ return Err(PdfError::ResourceLimit);
+ }
+ let mut document = Document::new();
+ let mut fonts = text::FontCache::default();
+ let mut images = std::collections::HashMap::new();
+ let scopes = primitives::scope_ends(&snapshot.fragments)?;
+ for page_index in selected {
+ let top = page_index as f64 * page_height;
+ let source = Rect::new(0.0, top, printable_width / scale, top + page_height);
+ let mut page = document.start_page_with(
+ PageSettings::from_wh(options.width as f32, options.height as f32)
+ .ok_or(PdfError::InvalidParameters)?,
+ );
+ let mut surface = page.surface();
+ let target = Rect::new(
+ options.margin_left,
+ options.margin_top,
+ options.width - options.margin_right,
+ options.height - options.margin_bottom,
+ );
+ surface.push_clip_path(
+ &primitives::path(&target).ok_or(PdfError::InvalidParameters)?,
+ &Default::default(),
+ );
+ surface.push_transform(&primitives::transform(
+ Affine::translate((options.margin_left, options.margin_top - top * scale))
+ * Affine::scale(scale),
+ ));
+ let mut painter = PdfPainter::new(
+ &mut surface,
+ snapshot,
+ source,
+ page_height,
+ page_index,
+ &mut fonts,
+ &mut images,
+ );
+ painter.fill_canvas();
+ let result = painter.paint(&snapshot.fragments, &scopes);
+ drop(painter);
+ surface.pop();
+ surface.pop();
+ surface.finish();
+ page.finish();
+ result?;
+ }
+ let mut bytes = document
+ .finish()
+ .map_err(|error| PdfError::Encoding(format!("{error:?}")))?;
+ bytes.push(b'\n');
+ Ok(bytes)
+}
+
+fn rect(rect: PaintRect) -> Rect {
+ Rect::new(
+ f64::from(rect.x),
+ f64::from(rect.y),
+ f64::from(rect.x + rect.width),
+ f64::from(rect.y + rect.height),
+ )
+}
+
+fn image_size(width: u32, height: u32) -> Result<Size, PdfError> {
+ Size::from_wh(width as f32, height as f32).ok_or(PdfError::InvalidParameters)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/moli-paint/src/pdf/primitives.rs b/moli-paint/src/pdf/primitives.rs
new file mode 100644
index 000000000..4929728a6
--- /dev/null
+++ b/moli-paint/src/pdf/primitives.rs
@@ -0,0 +1,807 @@
+use std::collections::HashMap;
+
+use anyrender::{Paint, Scene, recording::RenderCommand};
+use krilla::{
+ color::rgb,
+ geom::{Path, PathBuilder, Transform},
+ image::Image,
+ num::NormalizedF32,
+ paint::{Fill, FillRule, Stroke},
+ surface::Surface,
+};
+use moli_layout::{
+ PaintBlendMode, PaintCaptureSurface, PaintColor, PaintCompositeMode, PaintFragment,
+ PaintGlyphRun, PaintSnapshot, PaintTransform2D,
+};
+use peniko::kurbo::{Affine, PathEl, Rect, Shape};
+
+use super::{PdfError, text::FontCache};
+
+pub(super) fn transform(affine: Affine) -> Transform {
+ let [a, b, c, d, e, f] = affine.as_coeffs().map(|v| v as f32);
+ Transform::from_row(a, b, c, d, e, f)
+}
+pub(super) fn path(shape: &impl Shape) -> Option<Path> {
+ let mut out = PathBuilder::new();
+ for el in shape.path_elements(0.1) {
+ match el {
+ PathEl::MoveTo(p) => out.move_to(p.x as f32, p.y as f32),
+ PathEl::LineTo(p) => out.line_to(p.x as f32, p.y as f32),
+ PathEl::QuadTo(p, q) => out.quad_to(p.x as f32, p.y as f32, q.x as f32, q.y as f32),
+ PathEl::CurveTo(p, q, r) => out.cubic_to(
+ p.x as f32, p.y as f32, q.x as f32, q.y as f32, r.x as f32, r.y as f32,
+ ),
+ PathEl::ClosePath => out.close(),
+ }
+ }
+ out.finish()
+}
+pub(super) fn unit(value: f32) -> NormalizedF32 {
+ NormalizedF32::new(if value.is_finite() {
+ value.clamp(0.0, 1.0)
+ } else {
+ 0.0
+ })
+ .unwrap()
+}
+pub(super) fn fill(color: PaintColor) -> Fill {
+ let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ Fill {
+ paint: rgb::Color::new(
+ channel(color.red),
+ channel(color.green),
+ channel(color.blue),
+ )
+ .into(),
+ opacity: unit(color.alpha),
+ rule: FillRule::NonZero,
+ }
+}
+
+/// Resolve matching pops once and mark enclosing groups that must be isolated
+/// together. A destination mask must include the destination it modifies.
+pub(super) fn scope_ends(fragments: &[PaintFragment]) -> Result<Vec<(usize, bool)>, PdfError> {
+ let mut scopes = vec![(0, false); fragments.len()];
+ let mut stack: Vec<usize> = Vec::new();
+ for (i, fragment) in fragments.iter().enumerate() {
+ match fragment {
+ PaintFragment::PushLayer {
+ filter,
+ blend_mode,
+ composite,
+ ..
+ } => {
+ if *composite != PaintCompositeMode::SrcOver
+ || *blend_mode == PaintBlendMode::PlusLighter
+ {
+ // These operators consume the destination as well as their
+ // source. A source-only fallback would change the result.
+ let parent = stack.iter().rev().find(|&&parent| {
+ matches!(
+ fragments[parent],
+ PaintFragment::PushLayer {
+ composite: PaintCompositeMode::SrcOver,
+ ..
+ }
+ )
+ });
+ let Some(&parent) = parent else {
+ return Err(PdfError::Encoding(
+ "destination-dependent compositing requires an isolated parent layer"
+ .into(),
+ ));
+ };
+ scopes[parent].1 = true;
+ }
+ scopes[i].1 = filter.is_some()
+ || *blend_mode == PaintBlendMode::PlusLighter
+ || *composite != PaintCompositeMode::SrcOver;
+ stack.push(i);
+ }
+ PaintFragment::PushClip { .. } => stack.push(i),
+ PaintFragment::PopLayer => {
+ let start = stack.pop().expect("validated paint scopes");
+ scopes[start].0 = i;
+ }
+ _ => {}
+ }
+ }
+ Ok(scopes)
+}
+
+pub(super) struct PdfPainter<'a, 's> {
+ pub surface: &'a mut Surface<'s>,
+ snapshot: &'a PaintSnapshot,
+ pub source: Rect,
+ page_height: f64,
+ page_index: usize,
+ fonts: &'a mut FontCache,
+ images: &'a mut HashMap<(usize, bool), Image>,
+ clips: Vec<Rect>,
+ clip_shapes: Vec<PaintFragment>,
+ layers: Vec<usize>,
+}
+impl<'a, 's> PdfPainter<'a, 's> {
+ pub fn new(
+ surface: &'a mut Surface<'s>,
+ snapshot: &'a PaintSnapshot,
+ source: Rect,
+ page_height: f64,
+ page_index: usize,
+ fonts: &'a mut FontCache,
+ images: &'a mut HashMap<(usize, bool), Image>,
+ ) -> Self {
+ Self {
+ surface,
+ snapshot,
+ source,
+ page_height,
+ page_index,
+ fonts,
+ images,
+ clips: vec![Rect::new(
+ 0.0,
+ 0.0,
+ source.x1,
+ snapshot.surface.css_height as f64,
+ )],
+ clip_shapes: Vec::new(),
+ layers: Vec::new(),
+ }
+ }
+ pub fn fill_canvas(&mut self) {
+ self.surface
+ .set_fill(Some(fill(self.snapshot.canvas_color)));
+ self.surface.set_stroke(None);
+ if let Some(path) = path(&self.source.intersect(Rect::new(
+ 0.0,
+ 0.0,
+ self.snapshot.surface.css_width as f64,
+ self.snapshot.surface.css_height as f64,
+ ))) {
+ self.surface.draw_path(&path);
+ }
+ }
+ pub fn paint(
+ &mut self,
+ fragments: &[PaintFragment],
+ scopes: &[(usize, bool)],
+ ) -> Result<(), PdfError> {
+ let mut i = 0;
+ while i < fragments.len() {
+ let fragment = &fragments[i];
+ if matches!(fragment, PaintFragment::PushLayer { opacity, filter, .. }
+ if *opacity <= 0.0 || matches!(filter, Some(moli_layout::PaintFilter::Opacity(value)) if *value <= 0.0))
+ {
+ i = scopes[i].0 + 1;
+ continue;
+ }
+ if scopes[i].1 {
+ let end = scopes[i].0;
+ if self.rasterize(&fragments[i..=end])? {
+ self.effect_text(&fragments[i..=end])?;
+ }
+ i = end + 1;
+ continue;
+ }
+ match fragment {
+ PaintFragment::GlyphRun(run) => self.glyphs(run, false)?,
+ PaintFragment::TextShadow(_) | PaintFragment::BoxShadow(_) => {
+ self.rasterize(std::slice::from_ref(fragment))?;
+ }
+ PaintFragment::PushClip {
+ shape,
+ transform: matrix,
+ } => {
+ self.push_clip(shape, *matrix);
+ self.layers.push(1);
+ }
+ PaintFragment::PushLayer {
+ clip,
+ transform: matrix,
+ opacity,
+ blend_mode,
+ ..
+ } => {
+ self.push_clip(clip, *matrix);
+ self.surface.push_isolated();
+ self.surface.push_blend_mode(blend(*blend_mode));
+ self.surface.push_opacity(unit(*opacity));
+ self.layers.push(4);
+ }
+ PaintFragment::PopLayer => {
+ for _ in 0..self.layers.pop().expect("validated layers") {
+ self.surface.pop();
+ }
+ self.clips.pop();
+ self.clip_shapes.pop();
+ }
+ PaintFragment::Image(image) => {
+ let resource = self.snapshot.image(image.image).expect("validated image");
+ let interpolate = image.sampling == moli_layout::PaintImageSampling::Linear;
+ let key = (image.image.index(), interpolate);
+ if let std::collections::hash_map::Entry::Vacant(entry) = self.images.entry(key)
+ {
+ entry.insert(super::image::from_rgba(&resource.image, interpolate)?);
+ }
+ let data = self.images[&key].clone();
+ let matrix = crate::raster::to_backend_transform(image.transform)
+ * Affine::translate((
+ image.destination.x as f64,
+ image.destination.y as f64,
+ ))
+ * Affine::scale_non_uniform(
+ image.destination.width as f64 / resource.image.width as f64,
+ image.destination.height as f64 / resource.image.height as f64,
+ );
+ self.surface.push_transform(&transform(matrix));
+ self.surface.draw_image(
+ data,
+ super::image_size(resource.image.width, resource.image.height)?,
+ );
+ self.surface.pop();
+ }
+ _ => {
+ // Share the existing lowering of border styles, decorations,
+ // gradients and SVG paths. Text bypasses AnyRender entirely.
+ let mut scene = Scene::new();
+ crate::raster::paint_fragment(&mut scene, self.snapshot, fragment, 1.0);
+ if supported(&scene) {
+ self.commands(scene)?;
+ } else {
+ self.rasterize(std::slice::from_ref(fragment))?;
+ }
+ }
+ }
+ i += 1;
+ }
+ Ok(())
+ }
+ fn push_clip(&mut self, shape: &moli_layout::PaintShape, matrix: PaintTransform2D) {
+ self.clip_shapes.push(PaintFragment::PushClip {
+ shape: shape.clone(),
+ transform: matrix,
+ });
+ let shape = crate::raster::to_backend_shape(shape);
+ let matrix = crate::raster::to_backend_transform(matrix);
+ let shape = matrix * shape;
+ let bounds = self.clips.last().unwrap().intersect(shape.bounding_box());
+ self.clips.push(bounds);
+ // A degenerate clip must remain empty, never turn into an absent clip.
+ let clip = path(&shape).or_else(|| path(&Rect::ZERO)).unwrap();
+ self.surface.push_clip_path(&clip, &FillRule::NonZero);
+ }
+ fn glyphs(&mut self, run: &PaintGlyphRun, invisible: bool) -> Result<(), PdfError> {
+ super::text::draw(
+ self.surface,
+ self.snapshot,
+ run,
+ self.fonts,
+ *self.clips.last().unwrap(),
+ self.source,
+ &self.clip_shapes,
+ self.page_height,
+ self.page_index,
+ invisible,
+ )
+ }
+ fn effect_text(&mut self, fragments: &[PaintFragment]) -> Result<(), PdfError> {
+ // A transparent text overlay is valid for ordinary filters, but not for
+ // arbitrary destination masks: those can erase only part of a cluster.
+ // Refuse that combination until its coverage can be proven, rather
+ // than exporting invisible source text. Entirely transparent groups
+ // have already been eliminated by the raster result's alpha channel.
+ if fragments.iter().any(|f| {
+ matches!(f,
+ PaintFragment::PushLayer { composite, .. } if *composite != PaintCompositeMode::SrcOver)
+ }) && fragments.iter().any(|f| {
+ matches!(f,
+ PaintFragment::GlyphRun(run) if run.text.is_some() && run.color.alpha > 0.0)
+ }) {
+ return Err(PdfError::Encoding(
+ "searchable text inside destination masks is not supported".into(),
+ ));
+ }
+ let mut mask_depth = 0usize;
+ let mut masks = Vec::new();
+ let mut hidden = 0usize;
+ let mut result = Ok(());
+ for fragment in fragments {
+ match fragment {
+ PaintFragment::PushLayer {
+ clip,
+ transform,
+ composite,
+ opacity,
+ filter,
+ ..
+ } => {
+ let mask = *composite != PaintCompositeMode::SrcOver;
+ let transparent = *opacity <= 0.0
+ || matches!(filter, Some(moli_layout::PaintFilter::Opacity(value)) if *value <= 0.0);
+ masks.push((mask, transparent));
+ mask_depth += usize::from(mask);
+ hidden += usize::from(transparent);
+ self.push_clip(clip, *transform);
+ }
+ PaintFragment::PushClip { shape, transform } => {
+ masks.push((false, false));
+ self.push_clip(shape, *transform);
+ }
+ PaintFragment::PopLayer => {
+ let (mask, transparent) = masks.pop().unwrap();
+ mask_depth -= usize::from(mask);
+ hidden -= usize::from(transparent);
+ self.surface.pop();
+ self.clips.pop();
+ self.clip_shapes.pop();
+ }
+ PaintFragment::GlyphRun(run)
+ if mask_depth == 0 && hidden == 0 && run.text.is_some() && result.is_ok() =>
+ {
+ result = self.glyphs(run, true);
+ }
+ _ => {}
+ }
+ }
+ result
+ }
+ fn commands(&mut self, scene: Scene) -> Result<(), PdfError> {
+ for command in scene.commands {
+ match command {
+ RenderCommand::Fill(cmd) => {
+ self.surface.push_transform(&transform(cmd.transform));
+ self.surface.set_stroke(None);
+ self.surface.set_fill(Some(
+ brush(&cmd.brush, cmd.brush_transform, cmd.fill).unwrap(),
+ ));
+ if let Some(shape) = path(&cmd.shape) {
+ self.surface.draw_path(&shape);
+ }
+ self.surface.pop();
+ }
+ RenderCommand::Stroke(cmd) => {
+ let fill =
+ brush(&cmd.brush, cmd.brush_transform, peniko::Fill::NonZero).unwrap();
+ self.surface.push_transform(&transform(cmd.transform));
+ self.surface.set_fill(None);
+ self.surface.set_stroke(Some(Stroke {
+ paint: fill.paint,
+ opacity: fill.opacity,
+ width: cmd.style.width as f32,
+ miter_limit: cmd.style.miter_limit as f32,
+ line_cap: match cmd.style.start_cap {
+ peniko::kurbo::Cap::Butt => krilla::paint::LineCap::Butt,
+ peniko::kurbo::Cap::Round => krilla::paint::LineCap::Round,
+ peniko::kurbo::Cap::Square => krilla::paint::LineCap::Square,
+ },
+ line_join: match cmd.style.join {
+ peniko::kurbo::Join::Bevel => krilla::paint::LineJoin::Bevel,
+ peniko::kurbo::Join::Round => krilla::paint::LineJoin::Round,
+ peniko::kurbo::Join::Miter => krilla::paint::LineJoin::Miter,
+ },
+ dash: (!cmd.style.dash_pattern.is_empty()).then(|| {
+ krilla::paint::StrokeDash {
+ array: cmd.style.dash_pattern.iter().map(|v| *v as f32).collect(),
+ offset: cmd.style.dash_offset as f32,
+ }
+ }),
+ }));
+ if let Some(shape) = path(&cmd.shape) {
+ self.surface.draw_path(&shape);
+ }
+ self.surface.pop();
+ }
+ RenderCommand::PushClipLayer(cmd) => {
+ self.surface.push_clip_path(
+ &path(&(cmd.transform * cmd.clip)).unwrap(),
+ &FillRule::NonZero,
+ );
+ }
+ RenderCommand::PopLayer => self.surface.pop(),
+ _ => unreachable!("supported recording commands"),
+ }
+ }
+ Ok(())
+ }
+ fn rasterize(&mut self, fragments: &[PaintFragment]) -> Result<bool, PdfError> {
+ let Some(first) = fragments.first() else {
+ return Ok(false);
+ };
+ let extent = if fragments.len() > 1 {
+ effect_bounds(fragments).unwrap_or(self.source)
+ } else {
+ fragment_bounds(first).unwrap_or(self.source)
+ };
+ // Keep filter input beyond the page edge. Cropping it at the output
+ // clip would remove pixels that blur back into the printable area.
+ let padding = filter_padding(fragments);
+ let bounds = extent.intersect(
+ self.clips
+ .last()
+ .unwrap()
+ .intersect(self.source)
+ .inflate(padding, padding),
+ );
+ if bounds.width() <= 0.0 || bounds.height() <= 0.0 {
+ return Ok(false);
+ }
+ let bounds = bounds.expand();
+ let mut snapshot = PaintSnapshot::new(self.snapshot.viewport, PaintColor::TRANSPARENT);
+ snapshot.surface =
+ PaintCaptureSurface::new(bounds.width() as f32, bounds.height() as f32, 2.0);
+ snapshot.fonts = self.snapshot.fonts.clone();
+ snapshot.images = self.snapshot.images.clone();
+ snapshot.svg_images = self.snapshot.svg_images.clone();
+ snapshot.fragments = fragments.to_vec();
+ let outer_compositing = match snapshot.fragments.first_mut() {
+ Some(PaintFragment::PushLayer {
+ opacity,
+ blend_mode,
+ composite: PaintCompositeMode::SrcOver,
+ ..
+ }) => {
+ let saved = (*opacity, *blend_mode);
+ *opacity = 1.0;
+ *blend_mode = PaintBlendMode::Normal;
+ Some(saved)
+ }
+ _ => None,
+ };
+ let translation = Affine::translate((-bounds.x0, -bounds.y0));
+ for fragment in &mut snapshot.fragments {
+ translate_fragment(fragment, translation);
+ }
+ let image = crate::raster_snapshot(&snapshot)?;
+ if image
+ .rgba
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .all(|pixel| pixel[3] == 0)
+ {
+ return Ok(false);
+ }
+ let size = super::image_size(image.width, image.height)?;
+ if let Some((opacity, mode)) = outer_compositing {
+ self.surface.push_blend_mode(blend(mode));
+ self.surface.push_opacity(unit(opacity));
+ }
+ self.surface.push_transform(&transform(
+ Affine::translate((bounds.x0, bounds.y0)) * Affine::scale(0.5),
+ ));
+ self.surface.draw_image(
+ Image::from_rgba8(image.rgba, image.width, image.height),
+ size,
+ );
+ self.surface.pop();
+ if outer_compositing.is_some() {
+ self.surface.pop();
+ self.surface.pop();
+ }
+ Ok(true)
+ }
+}
+fn fragment_bounds(fragment: &PaintFragment) -> Option<Rect> {
+ let (bounds, matrix) = match fragment {
+ PaintFragment::Fill {
+ shape, transform, ..
+ }
+ | PaintFragment::PushClip { shape, transform } => (super::rect(shape.bounds()), *transform),
+ PaintFragment::PushLayer {
+ clip, transform, ..
+ } => (super::rect(clip.bounds()), *transform),
+ PaintFragment::SvgImage(image) => (super::rect(image.destination), image.transform),
+ PaintFragment::Image(image) => (super::rect(image.destination), image.transform),
+ PaintFragment::Border {
+ rect, transform, ..
+ } => (super::rect(*rect), *transform),
+ PaintFragment::Stroke(stroke) => (
+ super::rect(stroke.path.bounds).inflate(
+ (stroke.width * stroke.miter_limit.max(1.0)) as f64,
+ (stroke.width * stroke.miter_limit.max(1.0)) as f64,
+ ),
+ stroke.transform,
+ ),
+ PaintFragment::TextDecoration(decoration) => (
+ Rect::new(
+ decoration.x as f64,
+ decoration.y as f64,
+ (decoration.x + decoration.width) as f64,
+ decoration.y as f64,
+ )
+ .inflate(
+ decoration.thickness as f64 * 4.0,
+ decoration.thickness as f64 * 4.0,
+ ),
+ decoration.transform,
+ ),
+ PaintFragment::GlyphRun(run) => (glyph_bounds(run), run.transform),
+ PaintFragment::BoxShadow(shadow) => (
+ super::rect(shadow.rect).inflate(
+ (shadow.blur_radius * 3.0 + shadow.spread_radius.abs() + shadow.offset.x.abs())
+ as f64,
+ (shadow.blur_radius * 3.0 + shadow.spread_radius.abs() + shadow.offset.y.abs())
+ as f64,
+ ),
+ shadow.transform,
+ ),
+ PaintFragment::TextShadow(shadow) => {
+ let mut bounds = Rect::ZERO;
+ for (i, g) in shadow.run.glyphs.iter().enumerate() {
+ let point = Rect::new(g.x as f64, g.y as f64, g.x as f64, g.y as f64);
+ bounds = if i == 0 { point } else { bounds.union(point) };
+ }
+ let padding = (shadow.run.font_size * 2.0
+ + shadow.blur_radius * 3.0
+ + shadow.offset.x.abs().max(shadow.offset.y.abs()))
+ as f64;
+ (bounds.inflate(padding, padding), shadow.run.transform)
+ }
+ _ => return None,
+ };
+ Some(crate::raster::to_backend_transform(matrix).transform_rect_bbox(bounds))
+}
+fn translate_fragment(fragment: &mut PaintFragment, translation: Affine) {
+ let matrix = match fragment {
+ PaintFragment::PushLayer { transform, .. }
+ | PaintFragment::PushClip { transform, .. }
+ | PaintFragment::Fill { transform, .. }
+ | PaintFragment::Border { transform, .. } => transform,
+ PaintFragment::Stroke(stroke) => &mut stroke.transform,
+ PaintFragment::BoxShadow(shadow) => &mut shadow.transform,
+ PaintFragment::TextDecoration(decoration) => &mut decoration.transform,
+ PaintFragment::TextShadow(shadow) => &mut shadow.run.transform,
+ PaintFragment::GlyphRun(run) => &mut run.transform,
+ PaintFragment::Image(image) => &mut image.transform,
+ PaintFragment::SvgImage(image) => &mut image.transform,
+ PaintFragment::PopLayer => return,
+ };
+ *matrix = PaintTransform2D::new(
+ (translation * crate::raster::to_backend_transform(*matrix)).as_coeffs(),
+ );
+}
+
+/// For curved/rotated clips a bounding-box intersection is not sufficient to
+/// decide whether text exists in the visible result. Probe only the candidate
+/// cluster's clipped ink, with the same CPU clip implementation as screenshots.
+/// The PDF glyph itself is still emitted natively. Axis-aligned rectangular
+/// clips are already resolved exactly by the caller's bounds intersection.
+pub(super) fn visible_cluster_bounds(
+ snapshot: &PaintSnapshot,
+ run: &PaintGlyphRun,
+ range: std::ops::Range<usize>,
+ bounds: Rect,
+ clips: &[PaintFragment],
+ whitespace: bool,
+) -> Result<Option<Rect>, PdfError> {
+ if clips.iter().all(|clip| {
+ matches!(clip,
+ PaintFragment::PushClip { shape: moli_layout::PaintShape::Rect(_), transform }
+ if transform.coefficients[1] == 0.0 && transform.coefficients[2] == 0.0)
+ }) {
+ return Ok(Some(bounds));
+ }
+ let bounds = bounds.expand();
+ let mut probe = PaintSnapshot::new(snapshot.viewport, PaintColor::TRANSPARENT);
+ probe.surface = PaintCaptureSurface::new(bounds.width() as f32, bounds.height() as f32, 2.0);
+ probe.fonts = snapshot.fonts.clone();
+ probe.fragments = clips.to_vec();
+ let mut run = run.clone();
+ run.glyphs = run.glyphs[range].to_vec();
+ run.text = None;
+ if whitespace {
+ probe.fragments.push(PaintFragment::Fill {
+ shape: moli_layout::PaintShape::Rect(moli_layout::PaintRect::new(
+ bounds.x0 as f32,
+ bounds.y0 as f32,
+ bounds.width() as f32,
+ bounds.height() as f32,
+ )),
+ brush: moli_layout::PaintBrush::Solid(PaintColor::BLACK),
+ transform: PaintTransform2D::IDENTITY,
+ });
+ } else {
+ probe.fragments.push(PaintFragment::GlyphRun(run));
+ }
+ probe
+ .fragments
+ .extend(clips.iter().map(|_| PaintFragment::PopLayer));
+ let translation = Affine::translate((-bounds.x0, -bounds.y0));
+ for fragment in &mut probe.fragments {
+ translate_fragment(fragment, translation);
+ }
+ let pixels = crate::raster_snapshot(&probe)?;
+ let mut covered: Option<Rect> = None;
+ for (i, pixel) in pixels.rgba.as_chunks::<4>().0.iter().enumerate() {
+ if pixel[3] != 0 {
+ let x = bounds.x0 + (i % pixels.width as usize) as f64 * 0.5;
+ let y = bounds.y0 + (i / pixels.width as usize) as f64 * 0.5;
+ let pixel = Rect::new(x, y, x + 0.5, y + 0.5);
+ covered = Some(covered.map_or(pixel, |rect| rect.union(pixel)));
+ }
+ }
+ Ok(covered)
+}
+fn supported(scene: &Scene) -> bool {
+ scene.commands.iter().all(|command| match command {
+ RenderCommand::Fill(cmd) => brush(&cmd.brush, cmd.brush_transform, cmd.fill).is_some(),
+ RenderCommand::Stroke(cmd) => {
+ cmd.style.start_cap == cmd.style.end_cap
+ && brush(&cmd.brush, cmd.brush_transform, peniko::Fill::NonZero).is_some()
+ }
+ RenderCommand::PushClipLayer(_) | RenderCommand::PopLayer => true,
+ _ => false,
+ })
+}
+fn brush(paint: &Paint, matrix: Option<Affine>, rule: peniko::Fill) -> Option<Fill> {
+ let fill_rule = match rule {
+ peniko::Fill::NonZero => FillRule::NonZero,
+ peniko::Fill::EvenOdd => FillRule::EvenOdd,
+ };
+ match paint {
+ Paint::Solid(color) => {
+ let [r, g, b, a] = color.components;
+ let mut result = fill(PaintColor::new(r, g, b, a));
+ result.rule = fill_rule;
+ Some(result)
+ }
+ Paint::Gradient(gradient) => {
+ use krilla::paint::{LinearGradient, RadialGradient, SpreadMethod, Stop};
+ // Preserve non-sRGB interpolation and repeating radial gradients
+ // through the CPU fallback; PDF's native shading differs there.
+ if gradient.interpolation_cs != peniko::color::ColorSpaceTag::Srgb {
+ return None;
+ }
+ let stops = gradient
+ .stops
+ .iter()
+ .map(|stop| {
+ let color = stop.color.to_alpha_color::<peniko::color::Srgb>();
+ let [r, g, b, a] = color.components;
+ Stop {
+ offset: unit(stop.offset),
+ color: rgb::Color::new(
+ (r * 255.0).round() as u8,
+ (g * 255.0).round() as u8,
+ (b * 255.0).round() as u8,
+ )
+ .into(),
+ opacity: unit(a),
+ }
+ })
+ .collect();
+ let spread_method = match gradient.extend {
+ peniko::Extend::Pad => SpreadMethod::Pad,
+ peniko::Extend::Repeat => SpreadMethod::Repeat,
+ peniko::Extend::Reflect => SpreadMethod::Reflect,
+ };
+ let matrix = transform(matrix.unwrap_or(Affine::IDENTITY));
+ let paint = match gradient.kind {
+ peniko::GradientKind::Linear(line) => LinearGradient {
+ x1: line.start.x as f32,
+ y1: line.start.y as f32,
+ x2: line.end.x as f32,
+ y2: line.end.y as f32,
+ transform: matrix,
+ spread_method,
+ stops,
+ anti_alias: true,
+ }
+ .into(),
+ peniko::GradientKind::Radial(radial) if gradient.extend == peniko::Extend::Pad => {
+ RadialGradient {
+ fx: radial.start_center.x as f32,
+ fy: radial.start_center.y as f32,
+ fr: radial.start_radius,
+ cx: radial.end_center.x as f32,
+ cy: radial.end_center.y as f32,
+ cr: radial.end_radius,
+ transform: matrix,
+ spread_method,
+ stops,
+ anti_alias: true,
+ }
+ .into()
+ }
+ _ => return None,
+ };
+ Some(Fill {
+ paint,
+ opacity: NormalizedF32::ONE,
+ rule: fill_rule,
+ })
+ }
+ _ => None,
+ }
+}
+fn blend(mode: PaintBlendMode) -> krilla::blend::BlendMode {
+ use krilla::blend::BlendMode as B;
+ match mode {
+ PaintBlendMode::Normal | PaintBlendMode::PlusLighter => B::Normal,
+ PaintBlendMode::Multiply => B::Multiply,
+ PaintBlendMode::Screen => B::Screen,
+ PaintBlendMode::Overlay => B::Overlay,
+ PaintBlendMode::Darken => B::Darken,
+ PaintBlendMode::Lighten => B::Lighten,
+ PaintBlendMode::ColorDodge => B::ColorDodge,
+ PaintBlendMode::ColorBurn => B::ColorBurn,
+ PaintBlendMode::HardLight => B::HardLight,
+ PaintBlendMode::SoftLight => B::SoftLight,
+ PaintBlendMode::Difference => B::Difference,
+ PaintBlendMode::Exclusion => B::Exclusion,
+ PaintBlendMode::Hue => B::Hue,
+ PaintBlendMode::Saturation => B::Saturation,
+ PaintBlendMode::Color => B::Color,
+ PaintBlendMode::Luminosity => B::Luminosity,
+ }
+}
+
+impl Drop for PdfPainter<'_, '_> {
+ fn drop(&mut self) {
+ // Krilla requires balanced scopes even when encoding fails partway through a page.
+ for count in self.layers.drain(..).rev() {
+ for _ in 0..count {
+ self.surface.pop();
+ }
+ }
+ }
+}
+
+fn glyph_bounds(run: &PaintGlyphRun) -> Rect {
+ let mut bounds = Rect::ZERO;
+ for (i, glyph) in run.glyphs.iter().enumerate() {
+ let point = Rect::new(
+ glyph.x as f64,
+ glyph.y as f64,
+ glyph.x as f64,
+ glyph.y as f64,
+ );
+ bounds = if i == 0 { point } else { bounds.union(point) };
+ }
+ // Conservative ink extent for fallback allocation, including synthesis.
+ bounds.inflate(run.font_size as f64 * 2.0, run.font_size as f64 * 2.0)
+}
+fn filter_padding(fragments: &[PaintFragment]) -> f64 {
+ fragments
+ .iter()
+ .filter_map(|fragment| {
+ let PaintFragment::PushLayer {
+ filter: Some(filter),
+ transform,
+ ..
+ } = fragment
+ else {
+ return None;
+ };
+ let radius = match filter {
+ moli_layout::PaintFilter::Blur(radius) => radius * 3.0,
+ moli_layout::PaintFilter::DropShadow {
+ offset,
+ blur_radius,
+ ..
+ } => blur_radius * 3.0 + offset.x.abs().max(offset.y.abs()),
+ _ => 0.0,
+ };
+ let [a, b, c, d, _, _] = transform.coefficients;
+ Some(radius as f64 * (a.abs() + c.abs()).max(b.abs() + d.abs()))
+ })
+ .sum()
+}
+fn effect_bounds(fragments: &[PaintFragment]) -> Option<Rect> {
+ let mut bounds: Option<Rect> = None;
+ for fragment in fragments {
+ if matches!(
+ fragment,
+ PaintFragment::PushLayer { .. }
+ | PaintFragment::PushClip { .. }
+ | PaintFragment::PopLayer
+ ) {
+ continue;
+ }
+ let local = fragment_bounds(fragment)?;
+ bounds = Some(bounds.map_or(local, |bounds| bounds.union(local)));
+ }
+ let padding = filter_padding(fragments);
+ bounds.map(|bounds| bounds.inflate(padding, padding))
+}
diff --git a/moli-paint/src/pdf/tests.rs b/moli-paint/src/pdf/tests.rs
new file mode 100644
index 000000000..b7a0ee0ef
--- /dev/null
+++ b/moli-paint/src/pdf/tests.rs
@@ -0,0 +1,346 @@
+use std::sync::Arc;
+
+use moli_layout::{
+ PaintColor, PaintFragment, PaintGlyph, PaintGlyphRun, PaintPoint, PaintRect, PaintShape,
+ PaintSnapshot, PaintTextSemantics, PaintTransform2D, PaintViewport,
+};
+use skrifa::MetadataProvider;
+
+use super::*;
+
+fn snapshot() -> PaintSnapshot {
+ PaintSnapshot::new(PaintViewport::new(300, 600, 1.0), PaintColor::WHITE)
+}
+fn options() -> PdfOptions {
+ PdfOptions {
+ width: 300.0,
+ height: 300.0,
+ margin_top: 0.0,
+ margin_bottom: 0.0,
+ margin_left: 0.0,
+ margin_right: 0.0,
+ ..Default::default()
+ }
+}
+fn text(snapshot: &mut PaintSnapshot, text: &str, baseline: f32, cjk: bool) -> PaintGlyphRun {
+ let bytes: &[u8] = if cjk {
+ include_bytes!("../../../moli-layout/tests/fixtures/moli-cjk.ttf")
+ } else {
+ include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.ttf")
+ };
+ let font = peniko::FontData::new(peniko::Blob::new(Arc::new(bytes.to_vec())), 0);
+ let face = skrifa::FontRef::from_index(bytes, 0).unwrap();
+ let mut glyphs = Vec::new();
+ let mut clusters = Vec::new();
+ for (i, (offset, ch)) in text.char_indices().enumerate() {
+ glyphs.push(PaintGlyph {
+ id: face.charmap().map(ch).unwrap().to_u32(),
+ x: 10.0 + i as f32 * 12.0,
+ y: baseline,
+ });
+ clusters.push(offset..offset + ch.len_utf8());
+ }
+ PaintGlyphRun {
+ font: snapshot.intern_font(&font),
+ font_size: 20.0,
+ normalized_coords: Vec::new(),
+ color: PaintColor::BLACK,
+ glyph_skew_radians: None,
+ glyph_embolden: PaintPoint::ZERO,
+ glyphs,
+ text: Some(PaintTextSemantics {
+ text: Arc::from(text),
+ clusters,
+ }),
+ transform: PaintTransform2D::IDENTITY,
+ }
+}
+fn document(snapshot: &PaintSnapshot, options: &PdfOptions) -> lopdf::Document {
+ let pdf = pdf_snapshot(snapshot, options).unwrap();
+ lopdf::Document::load_mem(&pdf).unwrap()
+}
+fn extracted(document: &lopdf::Document, pages: &[u32]) -> String {
+ document
+ .extract_text(pages)
+ .unwrap()
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+#[test]
+fn embeds_fonts_and_unicode_instead_of_a_page_image() {
+ let mut snapshot = snapshot();
+ let run = text(&mut snapshot, "Font Text 123", 35.0, false);
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ let chinese = text(&mut snapshot, "中文", 65.0, true);
+ snapshot.push_fragment(PaintFragment::GlyphRun(chinese));
+ let doc = document(&snapshot, &options());
+ assert_eq!(extracted(&doc, &[1, 2]), "Font Text 123 中文");
+ assert!(
+ doc.objects
+ .values()
+ .any(|o| o.as_dict().is_ok_and(|d| d.has(b"FontFile2")))
+ );
+ assert!(
+ !doc.objects.values().any(|o| o.as_stream().is_ok_and(|s| s
+ .dict
+ .get(b"Subtype")
+ .and_then(|o| o.as_name())
+ .ok()
+ == Some(b"Image")))
+ );
+}
+#[test]
+fn pagination_and_ranges_do_not_duplicate_or_leak_text() {
+ let mut snapshot = snapshot();
+ for (label, y) in [("First", 40.0), ("Boundary", 302.0), ("Second", 350.0)] {
+ let run = text(&mut snapshot, label, y, false);
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ }
+ let doc = document(&snapshot, &options());
+ assert_eq!(extracted(&doc, &[1]), "First Boundary");
+ assert_eq!(extracted(&doc, &[2]), "Second");
+ let selected = document(
+ &snapshot,
+ &PdfOptions {
+ page_ranges: vec![1..=1],
+ ..options()
+ },
+ );
+ assert_eq!(selected.get_pages().len(), 1);
+ assert_eq!(extracted(&selected, &[1]), "Second");
+ assert!(matches!(
+ pdf_snapshot(
+ &snapshot,
+ &PdfOptions {
+ page_ranges: vec![100..=usize::MAX],
+ ..options()
+ }
+ ),
+ Err(PdfError::PageRangeExceeded)
+ ));
+}
+#[test]
+fn shadows_masks_and_filtered_text_have_one_semantic_copy() {
+ use moli_layout::{PaintBlendMode, PaintCompositeMode, PaintFilter, PaintTextShadow};
+ let mut snapshot = snapshot();
+ let run = text(&mut snapshot, "Shadow", 35.0, false);
+ snapshot.push_fragment(PaintFragment::TextShadow(PaintTextShadow {
+ run: run.clone(),
+ color: PaintColor::BLACK,
+ offset: PaintPoint::new(2.0, 2.0),
+ blur_radius: 2.0,
+ }));
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ let run = text(&mut snapshot, "Filtered", 90.0, false);
+ snapshot.push_fragment(PaintFragment::PushLayer {
+ opacity: 1.0,
+ blend_mode: PaintBlendMode::Normal,
+ composite: PaintCompositeMode::SrcOver,
+ clip: PaintShape::Rect(PaintRect::new(0.0, 60.0, 200.0, 50.0)),
+ transform: PaintTransform2D::IDENTITY,
+ filter: Some(PaintFilter::Blur(1.0)),
+ });
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ let mut run = text(&mut snapshot, "Mask", 140.0, false);
+ run.text = None;
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ let doc = document(&snapshot, &options());
+ assert_eq!(extracted(&doc, &[1, 2]), "Shadow Filtered");
+}
+#[test]
+fn clips_exclude_off_page_text_and_dpr_does_not_change_pagination() {
+ let mut snapshot = snapshot();
+ snapshot.push_fragment(PaintFragment::push_clip(PaintRect::new(
+ 0.0, 0.0, 300.0, 60.0,
+ )));
+ for (label, y) in [("Visible", 35.0), ("Hidden", 100.0)] {
+ let run = text(&mut snapshot, label, y, false);
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ }
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ let doc = document(&snapshot, &options());
+ assert_eq!(extracted(&doc, &[1, 2]), "Visible");
+ snapshot.surface.device_scale = 3.0;
+ let high_dpi = document(&snapshot, &options());
+ assert_eq!(high_dpi.get_pages().len(), doc.get_pages().len());
+ assert_eq!(extracted(&high_dpi, &[1, 2]), "Visible");
+}
+#[test]
+fn rejects_malformed_semantics_and_layer_streams() {
+ let mut snapshot = snapshot();
+ let mut run = text(&mut snapshot, "Bad", 35.0, false);
+ run.text.as_mut().unwrap().clusters[0] = 0..999;
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ assert!(matches!(
+ pdf_snapshot(&snapshot, &options()),
+ Err(PdfError::Encoding(_))
+ ));
+ snapshot.fragments = vec![PaintFragment::PopLayer];
+ assert!(matches!(
+ pdf_snapshot(&snapshot, &options()),
+ Err(PdfError::Paint(_))
+ ));
+}
+
+#[test]
+fn variable_fonts_invert_avar_and_keep_distinct_instances() {
+ let bytes = include_bytes!("../../tests/fixtures/moli-pdf.ttf");
+ let coords = super::text::variation_coordinates(bytes, 0, &[12288]).unwrap();
+ assert_eq!(coords[0].0.get(), b"wght");
+ assert_eq!(coords[0].1, 650.0);
+ let mut snapshot = snapshot();
+ let font = peniko::FontData::new(peniko::Blob::new(Arc::new(bytes.to_vec())), 0);
+ let id = snapshot.intern_font(&font);
+ for (coords, y) in [(vec![0], 30.0), (vec![12288], 80.0)] {
+ let mut run = text(&mut snapshot, "Weight", y, false);
+ run.font = id;
+ run.normalized_coords = coords;
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ }
+ let doc = document(&snapshot, &options());
+ assert_eq!(extracted(&doc, &[1]), "Weight Weight");
+ let fonts = doc.get_page_fonts(doc.get_pages()[&1]).unwrap();
+ assert_eq!(
+ fonts.len(),
+ 2,
+ "different variable instances need distinct PDF font resources"
+ );
+}
+
+#[test]
+fn transparency_group_bounds_include_the_last_glyph_advance() {
+ let mut snapshot = snapshot();
+ let run = text(&mut snapshot, "Opacity", 50.0, false);
+ let right = run.glyphs.last().unwrap().x + 12.0;
+ snapshot.push_fragment(PaintFragment::PushLayer {
+ opacity: 0.5,
+ blend_mode: moli_layout::PaintBlendMode::Normal,
+ composite: moli_layout::PaintCompositeMode::SrcOver,
+ clip: PaintShape::Rect(PaintRect::new(0.0, 0.0, 300.0, 300.0)),
+ transform: PaintTransform2D::IDENTITY,
+ filter: None,
+ });
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ let document = document(&snapshot, &options());
+ let bounds: Vec<_> = document
+ .objects
+ .values()
+ .filter_map(|object| {
+ let stream = object.as_stream().ok()?;
+ if stream.dict.get(b"Subtype").ok()?.as_name().ok()? != b"Form" {
+ return None;
+ }
+ Some(
+ stream.dict.get(b"BBox").ok()?.as_array().ok()?[2]
+ .as_float()
+ .unwrap(),
+ )
+ })
+ .collect();
+ assert!(!bounds.is_empty());
+ assert!(
+ bounds.iter().any(|bound| *bound >= right - 0.01),
+ "opacity XObjects must not clip their final glyph: {bounds:?}"
+ );
+}
+
+#[test]
+fn hidden_masks_and_zero_opacity_do_not_export_source_text() {
+ use moli_layout::{PaintBlendMode, PaintCompositeMode};
+ let layer = |composite, opacity| PaintFragment::PushLayer {
+ opacity,
+ blend_mode: PaintBlendMode::Normal,
+ composite,
+ clip: PaintShape::Rect(PaintRect::new(0.0, 0.0, 300.0, 300.0)),
+ transform: PaintTransform2D::IDENTITY,
+ filter: None,
+ };
+ let mut snapshot = snapshot();
+ let hidden = text(&mut snapshot, "Hidden", 40.0, false);
+ snapshot.fragments = vec![
+ layer(PaintCompositeMode::SrcOver, 1.0),
+ PaintFragment::GlyphRun(hidden.clone()),
+ layer(PaintCompositeMode::DestIn, 1.0),
+ PaintFragment::PopLayer, // An empty mask removes all destination ink.
+ PaintFragment::PopLayer,
+ layer(PaintCompositeMode::SrcOver, 0.0),
+ PaintFragment::GlyphRun(hidden),
+ PaintFragment::PopLayer,
+ ];
+ assert_eq!(extracted(&document(&snapshot, &options()), &[1, 2]), "");
+ snapshot.fragments.insert(
+ 3,
+ PaintFragment::Fill {
+ shape: PaintShape::Rect(PaintRect::new(0.0, 0.0, 30.0, 100.0)),
+ brush: moli_layout::PaintBrush::Solid(PaintColor::BLACK),
+ transform: PaintTransform2D::IDENTITY,
+ },
+ );
+ assert!(
+ matches!(pdf_snapshot(&snapshot, &options()), Err(PdfError::Encoding(message))
+ if message.contains("destination masks"))
+ );
+}
+
+#[test]
+fn path_clips_test_ink_instead_of_only_the_clip_bounding_box() {
+ use moli_layout::{PaintPath, PaintPathElement as El};
+ let mut snapshot = snapshot();
+ snapshot.push_fragment(PaintFragment::PushClip {
+ shape: PaintShape::Path(PaintPath {
+ elements: vec![
+ El::MoveTo(PaintPoint::ZERO),
+ El::LineTo(PaintPoint::new(100.0, 0.0)),
+ El::LineTo(PaintPoint::new(0.0, 100.0)),
+ El::Close,
+ ],
+ bounds: PaintRect::new(0.0, 0.0, 100.0, 100.0),
+ }),
+ transform: PaintTransform2D::IDENTITY,
+ });
+ let visible = text(&mut snapshot, "Hi", 30.0, false);
+ let mut hidden = text(&mut snapshot, "No", 90.0, false);
+ for glyph in &mut hidden.glyphs {
+ glyph.x += 70.0;
+ }
+ snapshot.push_fragment(PaintFragment::GlyphRun(visible));
+ snapshot.push_fragment(PaintFragment::GlyphRun(hidden));
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ assert_eq!(extracted(&document(&snapshot, &options()), &[1, 2]), "Hi");
+}
+
+#[test]
+fn embedded_snapshot_rebases_fonts_and_preserves_owned_text() {
+ let mut parent = snapshot();
+ let parent_run = text(&mut parent, "中文", 30.0, true);
+ parent.push_fragment(PaintFragment::GlyphRun(parent_run));
+ let mut child = snapshot();
+ let child_run = text(&mut child, "Child", 30.0, false);
+ child.push_fragment(PaintFragment::GlyphRun(child_run));
+ parent.append_embedded_snapshot(
+ child,
+ PaintRect::new(0.0, 0.0, 100.0, 60.0),
+ PaintTransform2D::translation(40.0, 80.0),
+ );
+ assert_eq!(
+ extracted(&document(&parent, &options()), &[1, 2]),
+ "中文 Child"
+ );
+}
+
+#[test]
+fn boundary_cluster_ownership_follows_the_remaining_clipped_ink() {
+ let mut snapshot = snapshot();
+ let run = text(&mut snapshot, "Boundary", 302.0, false);
+ snapshot.push_fragment(PaintFragment::push_clip(PaintRect::new(
+ 0.0, 300.0, 300.0, 20.0,
+ )));
+ snapshot.push_fragment(PaintFragment::GlyphRun(run));
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ let doc = document(&snapshot, &options());
+ assert_eq!(extracted(&doc, &[1]), "");
+ assert_eq!(extracted(&doc, &[2]), "Boundary");
+}
diff --git a/moli-paint/src/pdf/text.rs b/moli-paint/src/pdf/text.rs
new file mode 100644
index 000000000..4080f174d
--- /dev/null
+++ b/moli-paint/src/pdf/text.rs
@@ -0,0 +1,286 @@
+use std::collections::HashMap;
+
+use krilla::{
+ geom::Point,
+ paint::Stroke,
+ surface::Surface,
+ text::{Font, GlyphId, KrillaGlyph, Tag},
+};
+use moli_layout::{PaintGlyphRun, PaintSnapshot};
+use peniko::kurbo::{Affine, Rect};
+use skrifa::raw::{FontRef, TableProvider};
+
+use super::{
+ PdfError,
+ primitives::{fill, transform},
+};
+
+#[derive(Default)]
+pub(super) struct FontCache(HashMap<(usize, Vec<i16>), Font>);
+impl FontCache {
+ fn get(&mut self, snapshot: &PaintSnapshot, run: &PaintGlyphRun) -> Result<Font, PdfError> {
+ let key = (run.font.index(), run.normalized_coords.clone());
+ if let Some(font) = self.0.get(&key) {
+ return Ok(font.clone());
+ }
+ let data = &snapshot.font(run.font).expect("validated font").font;
+ let coords = variation_coordinates(data.data.as_ref(), data.index, &run.normalized_coords)?;
+ let (bytes, _) = data.data.clone().into_raw_parts();
+ let font = Font::new_variable(bytes.into(), data.index, &coords)
+ .ok_or_else(|| PdfError::Encoding("font cannot be embedded".into()))?;
+ self.0.insert(key, font.clone());
+ Ok(font)
+ }
+}
+
+// Parley exports post-avar normalized coordinates; Krilla takes design-space
+// axes. Invert the avar v1 piecewise maps before denormalizing with fvar.
+pub(super) fn variation_coordinates(
+ data: &[u8],
+ index: u32,
+ coords: &[i16],
+) -> Result<Vec<(Tag, f32)>, PdfError> {
+ if coords.iter().all(|v| *v == 0) {
+ return Ok(Vec::new());
+ }
+ let font =
+ FontRef::from_index(data, index).map_err(|error| PdfError::Encoding(error.to_string()))?;
+ let fvar = font
+ .fvar()
+ .map_err(|error| PdfError::Encoding(error.to_string()))?;
+ let axes = fvar
+ .axes()
+ .map_err(|error| PdfError::Encoding(error.to_string()))?;
+ let avar = font.avar().ok();
+ if avar.as_ref().is_some_and(|avar| avar.version().major > 1) {
+ return Err(PdfError::Encoding(
+ "avar v2 font instances are not supported by the PDF adapter".into(),
+ ));
+ }
+ let mut result = Vec::new();
+ for (i, axis) in axes.iter().enumerate() {
+ let mut value = f32::from(coords.get(i).copied().unwrap_or(0)) / 16384.0;
+ if let Some(map) = avar
+ .as_ref()
+ .and_then(|a| a.axis_segment_maps().get(i)?.ok())
+ {
+ for pair in map.axis_value_maps().windows(2) {
+ let low = pair[0].to_coordinate().to_f32();
+ let high = pair[1].to_coordinate().to_f32();
+ if value >= low && value <= high && high > low {
+ let from = pair[0].from_coordinate().to_f32();
+ let to = pair[1].from_coordinate().to_f32();
+ value = from + (to - from) * (value - low) / (high - low);
+ break;
+ }
+ }
+ }
+ let default = axis.default_value().to_f32();
+ let value = default
+ + value
+ * if value < 0.0 {
+ default - axis.min_value().to_f32()
+ } else {
+ axis.max_value().to_f32() - default
+ };
+ result.push((Tag::new(&axis.axis_tag().to_be_bytes()), value));
+ }
+ Ok(result)
+}
+
+pub(super) fn draw(
+ surface: &mut Surface<'_>,
+ snapshot: &PaintSnapshot,
+ run: &PaintGlyphRun,
+ fonts: &mut FontCache,
+ clip: Rect,
+ page_clip: Rect,
+ clip_shapes: &[moli_layout::PaintFragment],
+ page_height: f64,
+ page_index: usize,
+ invisible: bool,
+) -> Result<(), PdfError> {
+ if run.glyphs.is_empty()
+ || !run.font_size.is_finite()
+ || run.font_size <= 0.0
+ || run.color.alpha <= 0.0
+ || clip.width() <= 0.0
+ || clip.height() <= 0.0
+ {
+ return Ok(());
+ }
+ if let Some(text) = &run.text
+ && (text.clusters.len() != run.glyphs.len()
+ || text
+ .clusters
+ .iter()
+ .any(|range| text.text.get(range.clone()).is_none()))
+ {
+ return Err(PdfError::Encoding(
+ "invalid glyph-to-text cluster mapping".into(),
+ ));
+ }
+ let matrix = crate::raster::to_backend_transform(run.transform);
+ let font = fonts.get(snapshot, run)?;
+ let font_size = run.font_size;
+ let skew = run.glyph_skew_radians.unwrap_or_default().tan();
+ let source_text = run.text.as_ref().map_or("", |text| text.text.as_ref());
+ let data = &snapshot.font(run.font).expect("validated font").font;
+ use skrifa::MetadataProvider;
+ let face = skrifa::FontRef::from_index(data.data.as_ref(), data.index)
+ .map_err(|error| PdfError::Encoding(error.to_string()))?;
+ let coords: Vec<_> = run
+ .normalized_coords
+ .iter()
+ .map(|v| skrifa::instance::NormalizedCoord::from_bits(*v))
+ .collect();
+ let metrics = face.glyph_metrics(skrifa::instance::Size::new(font_size), coords.as_slice());
+ let mut batches: Vec<(bool, Vec<usize>)> = Vec::new();
+ let mut start = 0;
+ while start < run.glyphs.len() {
+ let range = run
+ .text
+ .as_ref()
+ .map_or(0..0, |text| text.clusters[start].clone());
+ let mut end = start + 1;
+ if let Some(text) = &run.text {
+ while end < run.glyphs.len() && text.clusters[end] == range {
+ end += 1;
+ }
+ }
+ let last_page = (f64::from(snapshot.surface.css_height) / page_height)
+ .ceil()
+ .max(1.0) as usize
+ - 1;
+ let mut bounds: Option<Rect> = None;
+ for glyph in &run.glyphs[start..end] {
+ let id = skrifa::GlyphId::new(glyph.id);
+ let glyph_bounds = metrics
+ .bounds(id)
+ .filter(|b| b.x_max > b.x_min && b.y_max > b.y_min);
+ // Spaces and bitmap/color fonts may have no outline box. Retain
+ // their advance box, so spaces remain actual text in the PDF.
+ let local = glyph_bounds.map_or_else(
+ || {
+ Rect::new(
+ 0.0,
+ -font_size as f64,
+ metrics.advance_width(id).unwrap_or(font_size) as f64,
+ font_size as f64 * 0.2,
+ )
+ },
+ |b| {
+ Rect::new(
+ b.x_min as f64,
+ -b.y_max as f64,
+ b.x_max as f64,
+ -b.y_min as f64,
+ )
+ },
+ );
+ let glyph_matrix = matrix
+ * Affine::translate((glyph.x as f64, glyph.y as f64))
+ * Affine::skew(-skew as f64, 0.0);
+ let local = glyph_matrix
+ .transform_rect_bbox(local)
+ .inflate(run.glyph_embolden.x as f64, run.glyph_embolden.y as f64);
+ bounds = Some(bounds.map_or(local, |bounds| bounds.union(local)));
+ }
+ let bounds = bounds.unwrap().intersect(clip);
+ let on_page = bounds.intersect(page_clip);
+ if on_page.width() > 0.0
+ && on_page.height() > 0.0
+ && let Some(visible) = super::primitives::visible_cluster_bounds(
+ snapshot,
+ run,
+ start..end,
+ bounds,
+ clip_shapes,
+ source_text
+ .get(range)
+ .is_some_and(|text| !text.is_empty() && text.chars().all(char::is_whitespace)),
+ )?
+ {
+ // Use visible document-space ink before the page clip. If a clip
+ // erases one half of boundary text, its remaining ink owns the text.
+ let owner =
+ ((visible.center().y / page_height).floor().max(0.0) as usize).min(last_page);
+ let on_page = visible.intersect(page_clip);
+ if on_page.width() <= 0.0
+ || on_page.height() <= 0.0
+ || (invisible && owner != page_index)
+ {
+ start = end;
+ continue;
+ }
+ let outlined = run.text.is_none() || owner != page_index;
+ if batches
+ .last()
+ .is_none_or(|(previous, _)| *previous != outlined)
+ {
+ batches.push((outlined, Vec::new()));
+ }
+ batches.last_mut().unwrap().1.extend(start..end);
+ }
+ start = end;
+ }
+ for (outlined, indices) in batches {
+ let first = run.glyphs[indices[0]];
+ surface.push_transform(&transform(
+ matrix
+ * Affine::translate((first.x as f64, first.y as f64))
+ * Affine::skew(-(skew as f64), 0.0),
+ ));
+ let glyphs: Vec<_> = indices
+ .iter()
+ .enumerate()
+ .map(|(position, &i)| {
+ let glyph = run.glyphs[i];
+ let next = indices
+ .get(position + 1)
+ .map(|&i| run.glyphs[i].x)
+ .unwrap_or_else(|| {
+ glyph.x
+ + metrics
+ .advance_width(skrifa::GlyphId::new(glyph.id))
+ .unwrap_or(font_size)
+ });
+ KrillaGlyph {
+ glyph_id: GlyphId::new(glyph.id),
+ text_range: run
+ .text
+ .as_ref()
+ .map_or(0..0, |text| text.clusters[i].clone()),
+ x_advance: (next - glyph.x) / font_size,
+ y_advance: 0.0,
+ x_offset: skew * (glyph.y - first.y) / font_size,
+ y_offset: -(glyph.y - first.y) / font_size,
+ location: None,
+ }
+ })
+ .collect();
+ let mut paint = fill(run.color);
+ if invisible {
+ paint.opacity = krilla::num::NormalizedF32::ZERO;
+ }
+ surface.set_stroke(
+ (run.glyph_embolden.x > 0.0 || run.glyph_embolden.y > 0.0).then(|| Stroke {
+ paint: paint.paint.clone(),
+ opacity: paint.opacity,
+ width: 2.0 * run.glyph_embolden.x.max(run.glyph_embolden.y),
+ ..Default::default()
+ }),
+ );
+ surface.set_fill(Some(paint));
+ surface.draw_glyphs(
+ Point::from_xy(0.0, 0.0),
+ &glyphs,
+ font.clone(),
+ source_text,
+ font_size,
+ outlined,
+ );
+ surface.pop();
+ }
+ Ok(())
+}
diff --git a/moli-paint/src/pdf/validation.rs b/moli-paint/src/pdf/validation.rs
new file mode 100644
index 000000000..c3ebb6315
--- /dev/null
+++ b/moli-paint/src/pdf/validation.rs
@@ -0,0 +1,162 @@
+use moli_layout::*;
+
+use super::PdfError;
+
+// Validate owned commands before passing coordinates to Krilla (or a local
+// raster fallback). Resource identities, operation counts and scope depths are
+// checked by the shared paint validator.
+pub(super) fn validate(snapshot: &PaintSnapshot) -> Result<(), PdfError> {
+ for fragment in &snapshot.fragments {
+ let (valid, matrix) = match fragment {
+ PaintFragment::PushLayer {
+ clip,
+ transform,
+ opacity,
+ filter,
+ ..
+ } => (
+ shape(clip) && opacity.is_finite() && filter.is_none_or(valid_filter),
+ *transform,
+ ),
+ PaintFragment::PushClip {
+ shape: value,
+ transform,
+ } => (shape(value), *transform),
+ PaintFragment::Fill {
+ shape: value,
+ brush: paint,
+ transform,
+ } => (shape(value) && brush(paint), *transform),
+ PaintFragment::Stroke(stroke) => (
+ path(&stroke.path)
+ && finite([stroke.width, stroke.miter_limit, stroke.dash_offset])
+ && stroke.dash_pattern.iter().all(|v| v.is_finite()),
+ stroke.transform,
+ ),
+ PaintFragment::Border {
+ rect: value,
+ widths,
+ radii,
+ transform,
+ ..
+ } => (
+ rect(*value)
+ && finite([widths.top, widths.right, widths.bottom, widths.left])
+ && corners(*radii),
+ *transform,
+ ),
+ PaintFragment::BoxShadow(shadow) => (
+ rect(shadow.rect)
+ && corners(shadow.radii)
+ && point(shadow.offset)
+ && finite([shadow.blur_radius, shadow.spread_radius]),
+ shadow.transform,
+ ),
+ PaintFragment::TextDecoration(value) => (
+ finite([value.x, value.y, value.width, value.thickness]),
+ value.transform,
+ ),
+ PaintFragment::GlyphRun(run) => (glyphs(run), run.transform),
+ PaintFragment::TextShadow(shadow) => (
+ glyphs(&shadow.run) && point(shadow.offset) && shadow.blur_radius.is_finite(),
+ shadow.run.transform,
+ ),
+ PaintFragment::Image(image) => (rect(image.destination), image.transform),
+ PaintFragment::SvgImage(image) => (rect(image.destination), image.transform),
+ PaintFragment::PopLayer => continue,
+ };
+ if !valid
+ || !matrix
+ .coefficients
+ .into_iter()
+ .all(|v| (v as f32).is_finite())
+ {
+ return Err(PdfError::Encoding(
+ "invalid paint geometry or text mapping".into(),
+ ));
+ }
+ }
+ Ok(())
+}
+fn finite<const N: usize>(values: [f32; N]) -> bool {
+ values.into_iter().all(f32::is_finite)
+}
+fn point(p: PaintPoint) -> bool {
+ finite([p.x, p.y])
+}
+fn rect(r: PaintRect) -> bool {
+ finite([r.x, r.y, r.width, r.height, r.x + r.width, r.y + r.height])
+}
+fn corners(c: PaintCornerRadii) -> bool {
+ [c.top_left, c.top_right, c.bottom_left, c.bottom_right]
+ .into_iter()
+ .all(|r| finite([r.x, r.y]))
+}
+fn shape(s: &PaintShape) -> bool {
+ match s {
+ PaintShape::Rect(r) => rect(*r),
+ PaintShape::RoundedRect { rect: r, radii } => rect(*r) && corners(*radii),
+ PaintShape::Path(p) => path(p),
+ }
+}
+fn path(p: &PaintPath) -> bool {
+ rect(p.bounds)
+ && p.elements.iter().all(|element| match *element {
+ PaintPathElement::MoveTo(a) | PaintPathElement::LineTo(a) => point(a),
+ PaintPathElement::QuadTo(a, b) => point(a) && point(b),
+ PaintPathElement::CubicTo(a, b, c) => point(a) && point(b) && point(c),
+ PaintPathElement::Close => true,
+ })
+}
+fn glyphs(run: &PaintGlyphRun) -> bool {
+ run.font_size.is_finite()
+ && point(run.glyph_embolden)
+ && run
+ .glyph_skew_radians
+ .is_none_or(|v| v.is_finite() && v.tan().is_finite())
+ && run.glyphs.iter().all(|g| finite([g.x, g.y]))
+ && run.text.as_ref().is_none_or(|t| {
+ t.clusters.len() == run.glyphs.len()
+ && t.clusters.iter().all(|r| t.text.get(r.clone()).is_some())
+ })
+}
+fn stops(values: &[PaintGradientStop]) -> bool {
+ values.iter().all(|s| s.offset.is_finite())
+}
+fn brush(b: &PaintBrush) -> bool {
+ match b {
+ PaintBrush::Solid(_) => true,
+ PaintBrush::LinearGradient(g) => point(g.start) && point(g.end) && stops(&g.stops),
+ PaintBrush::RadialGradient(g) => {
+ point(g.start_center)
+ && point(g.end_center)
+ && finite([g.start_radius, g.end_radius])
+ && stops(&g.stops)
+ && g.transform.is_finite()
+ }
+ PaintBrush::ConicGradient(g) => {
+ point(g.center)
+ && finite([g.start_angle_radians, g.end_angle_radians])
+ && stops(&g.stops)
+ && g.transform.is_finite()
+ }
+ }
+}
+fn valid_filter(f: PaintFilter) -> bool {
+ match f {
+ PaintFilter::Blur(v)
+ | PaintFilter::Brightness(v)
+ | PaintFilter::Contrast(v)
+ | PaintFilter::Grayscale(v)
+ | PaintFilter::HueRotate(v)
+ | PaintFilter::Invert(v)
+ | PaintFilter::Opacity(v)
+ | PaintFilter::Saturate(v)
+ | PaintFilter::Sepia(v) => v.is_finite(),
+ PaintFilter::DropShadow {
+ offset,
+ blur_radius,
+ ..
+ } => point(offset) && blur_radius.is_finite(),
+ }
+}
diff --git a/moli-paint/src/raster/mod.rs b/moli-paint/src/raster/mod.rs
index ccf017cbd..c938305d9 100644
--- a/moli-paint/src/raster/mod.rs
+++ b/moli-paint/src/raster/mod.rs
@@ -263,13 +263,15 @@ fn unpremultiply_rgba(rgba: &mut [u8]) {
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-struct PaintStreamMetrics {
+pub(crate) struct PaintStreamMetrics {
max_filter_depth: usize,
glyph_count: usize,
- operation_count: usize,
+ pub(crate) operation_count: usize,
}
-fn validate_fragment_stream(snapshot: &PaintSnapshot) -> Result<PaintStreamMetrics, PaintError> {
+pub(crate) fn validate_fragment_stream(
+ snapshot: &PaintSnapshot,
+) -> Result<PaintStreamMetrics, PaintError> {
let mut layers = Vec::new();
let mut filter_depth = 0usize;
let mut metrics = PaintStreamMetrics {
@@ -604,7 +606,7 @@ fn matching_layer_pop(fragments: &[PaintFragment], push_index: usize) -> usize {
unreachable!("paint stream validation rejects unclosed layers")
}
-fn paint_fragment(
+pub(crate) fn paint_fragment(
scene: &mut impl PaintScene,
snapshot: &PaintSnapshot,
fragment: &PaintFragment,
@@ -1793,7 +1795,7 @@ fn backend_gradient_stops(stops: &[moli_layout::PaintGradientStop]) -> Vec<(f32,
.collect()
}
-fn to_backend_shape(shape: &PaintShape) -> BezPath {
+pub(crate) fn to_backend_shape(shape: &PaintShape) -> BezPath {
match shape {
PaintShape::Rect(rect) => to_backend_rect(*rect)
.map(|rect| rect_path(rect, true))
@@ -2002,7 +2004,7 @@ fn device_transform(transform: PaintTransform2D, scale: f64) -> Affine {
Affine::scale(scale) * to_backend_transform(transform)
}
-fn to_backend_transform(transform: PaintTransform2D) -> Affine {
+pub(crate) fn to_backend_transform(transform: PaintTransform2D) -> Affine {
if transform.is_finite() {
Affine::new(transform.coefficients)
} else {
@@ -2602,6 +2604,7 @@ mod tests {
let mut glyph = snapshot(2, 2, 1.0);
glyph.push_fragment(PaintFragment::GlyphRun(moli_layout::PaintGlyphRun {
+ text: None,
font: moli_layout::PaintFontId::from_index(0),
font_size: 12.0,
normalized_coords: Vec::new(),
@@ -2635,6 +2638,7 @@ mod tests {
);
let font = snapshot.intern_font(&font);
snapshot.push_fragment(PaintFragment::GlyphRun(moli_layout::PaintGlyphRun {
+ text: None,
font,
font_size: 50.0,
normalized_coords: Vec::new(),
diff --git a/moli-paint/tests/fixtures/moli-pdf.ttf b/moli-paint/tests/fixtures/moli-pdf.ttf
new file mode 100644
index 000000000..e5da1577b
Binary files /dev/null and b/moli-paint/tests/fixtures/moli-pdf.ttf differ
diff --git a/moli-protocol/Cargo.toml b/moli-protocol/Cargo.toml
index 2b1f8189a..4dfed44b5 100644
--- a/moli-protocol/Cargo.toml
+++ b/moli-protocol/Cargo.toml
@@ -49,6 +49,10 @@ http = "1"
sanitize-filename = "=0.6.0"
[dev-dependencies]
+moli-paint = { path = "../moli-paint" }
+moli-layout = { path = "../moli-layout" }
+lopdf = { version = "0.45.0", default-features = false }
+
tokio-tungstenite = { version = "0.28.0", default-features = false, features = ["handshake"] }
futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }
axum = { version = "0.8.6", features = ["ws"] }
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index dccefb40c..3f736fd90 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -127,22 +127,6 @@ fn missing_page_target_error_message(
}
}
-/// Builds a letter-sized raster PDF using the same defaults as
-/// `Page.printToPDF`.
-pub fn build_default_raster_pdf(
- jpeg: &[u8],
- image_width: u32,
- image_height: u32,
-) -> anyhow::Result<Vec<u8>> {
- pdf::build_raster_pdf(
- jpeg,
- image_width,
- image_height,
- &pdf::RasterPdfOptions::default(),
- )
- .map_err(|error| anyhow::anyhow!(error.message().to_owned()))
-}
-
use child_frame_activity::PagePreparedChildFrameDocumentActivity;
pub(crate) use child_frame_activity::{
PagePreparedChildFrameActivity, PagePreparedChildFrameTreeEvent,
@@ -247,7 +231,6 @@ enum PendingPageCommandKind {
},
PrintToPdf {
pending: PendingPageCommand,
- options: pdf::RasterPdfOptions,
transfer_mode: DevToolsPrintToPdfTransferMode,
},
Navigate(Box<navigation::PendingNavigateLoadCommand>),
@@ -315,7 +298,6 @@ enum CompletedPageCommandKind {
},
PrintToPdf {
completed: Box<Result<CompletedPageCommand, String>>,
- options: pdf::RasterPdfOptions,
transfer_mode: DevToolsPrintToPdfTransferMode,
},
Navigate(Box<navigation::CompletedNavigateLoadCommand>),
@@ -464,11 +446,9 @@ impl PendingPageCommandDispatch {
}
PendingPageCommandKind::PrintToPdf {
pending,
- options,
transfer_mode,
} => CompletedPageCommandKind::PrintToPdf {
completed: Box::new(pending.wait().await.map_err(|error| error.to_string())),
- options,
transfer_mode,
},
PendingPageCommandKind::Navigate(pending) => {
@@ -2329,7 +2309,6 @@ pub(crate) async fn complete_pending_page_command(
}
CompletedPageCommandKind::PrintToPdf {
completed,
- options,
transfer_mode,
} => {
let completion = match *completed {
@@ -2349,15 +2328,20 @@ pub(crate) async fn complete_pending_page_command(
));
}
};
- let image = match page.finish_capture_screenshot(completion) {
- Ok(RendererCaptureScreenshotReply::Captured(image)) => image,
- Ok(RendererCaptureScreenshotReply::LayoutDisabled) => {
+ let pdf = match page.finish_print_to_pdf(completion) {
+ Ok(moli_core::page::RendererPrintToPdfReply::Printed(bytes)) => bytes,
+ Ok(moli_core::page::RendererPrintToPdfReply::Failed(message)) => {
+ return PageCommandTaskStep::Complete(CommandOutputPlan::error(
+ -32000, message,
+ ));
+ }
+ Ok(moli_core::page::RendererPrintToPdfReply::LayoutDisabled) => {
return PageCommandTaskStep::Complete(CommandOutputPlan::error(
-32000,
PRINT_TO_PDF_LAYOUT_DISABLED_MESSAGE,
));
}
- Ok(RendererCaptureScreenshotReply::NoDocument) => {
+ Ok(moli_core::page::RendererPrintToPdfReply::NoDocument) => {
return PageCommandTaskStep::Complete(CommandOutputPlan::error(
-32000,
"NoDocumentLoaded",
@@ -2370,26 +2354,6 @@ pub(crate) async fn complete_pending_page_command(
));
}
};
- if image.mime_type != "image/jpeg" {
- return PageCommandTaskStep::Complete(CommandOutputPlan::error(
- -32000,
- "Printing failed: renderer returned a non-JPEG raster",
- ));
- }
- let pdf = match pdf::build_raster_pdf(
- image.bytes.as_ref(),
- image.width,
- image.height,
- &options,
- ) {
- Ok(pdf) => pdf,
- Err(error) => {
- return PageCommandTaskStep::Complete(CommandOutputPlan::error(
- error.code(),
- error.message(),
- ));
- }
- };
match transfer_mode {
DevToolsPrintToPdfTransferMode::ReturnAsBase64 => {
CommandOutputPlan::result(json!({
diff --git a/moli-protocol/src/domains/page/capture.rs b/moli-protocol/src/domains/page/capture.rs
index ae05bbc3b..8db884694 100644
--- a/moli-protocol/src/domains/page/capture.rs
+++ b/moli-protocol/src/domains/page/capture.rs
@@ -610,7 +610,7 @@ pub(super) fn start_devtools_print_to_pdf_command(
PRINT_TO_PDF_LAYOUT_DISABLED_MESSAGE,
));
}
- let options = match pdf::RasterPdfOptions::from_command(&command) {
+ let options = match pdf::PrintPdfOptions::from_command(&command) {
Ok(options) => options,
Err(error) => {
return PageCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -630,25 +630,15 @@ pub(super) fn start_devtools_print_to_pdf_command(
return PageCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message));
}
};
- let request = RendererCaptureScreenshotRequest {
- base_background_color: [255; 4],
- purpose: RendererScreenshotPurpose::Print {
- print_background: command.print_background.unwrap_or(false),
- },
- format: RendererScreenshotFormat::Jpeg,
- quality: 90,
- region: RendererScreenshotRegion::FullDocument,
- optimize_for_speed: false,
- max_width: None,
- max_height: None,
- };
- match page.start_capture_screenshot_with_request(request) {
+ match page.start_print_to_pdf(moli_core::page::RendererPrintToPdfRequest {
+ options: options.into_renderer_options(),
+ print_background: command.print_background.unwrap_or(false),
+ }) {
Ok(pending) => PageCommandTaskStep::Pending(PendingPageCommandDispatch {
command_id,
owner_scope,
kind: Box::new(PendingPageCommandKind::PrintToPdf {
pending,
- options,
transfer_mode,
}),
}),
diff --git a/moli-protocol/src/domains/page/pdf.rs b/moli-protocol/src/domains/page/pdf.rs
index 697b8b5bd..bba9d86d1 100644
--- a/moli-protocol/src/domains/page/pdf.rs
+++ b/moli-protocol/src/domains/page/pdf.rs
@@ -1,5 +1,3 @@
-use std::{collections::BTreeSet, io::Write as _};
-
use crate::automation::DevToolsPrintToPdfCommand;
const POINTS_PER_INCH: f64 = 72.0;
@@ -7,10 +5,9 @@ const DEFAULT_MARGIN_INCHES: f64 = 1.0 / 2.54;
const DEFAULT_PAGE_WIDTH_INCHES: f64 = 8.5;
const DEFAULT_PAGE_HEIGHT_INCHES: f64 = 11.0;
const MAX_PAGE_DIMENSION_INCHES: f64 = 200.0;
-const MAX_PAGE_COUNT: usize = 100_000;
#[derive(Clone, Debug, PartialEq)]
-pub(super) struct RasterPdfOptions {
+pub(super) struct PrintPdfOptions {
page_width_points: f64,
page_height_points: f64,
margin_top_points: f64,
@@ -21,7 +18,7 @@ pub(super) struct RasterPdfOptions {
page_ranges: Vec<PageRange>,
}
-impl Default for RasterPdfOptions {
+impl Default for PrintPdfOptions {
fn default() -> Self {
Self {
page_width_points: DEFAULT_PAGE_WIDTH_INCHES * POINTS_PER_INCH,
@@ -72,7 +69,7 @@ impl PdfError {
}
}
-impl RasterPdfOptions {
+impl PrintPdfOptions {
pub(super) fn from_command(command: &DevToolsPrintToPdfCommand) -> Result<Self, PdfError> {
let scale = command.scale.unwrap_or(1.0);
if !scale.is_finite() || !(0.1..=2.0).contains(&scale) {
@@ -118,32 +115,6 @@ impl RasterPdfOptions {
page_ranges: parse_page_ranges(command.page_ranges.as_deref().unwrap_or(""))?,
})
}
-
- fn printable_width(&self) -> f64 {
- self.page_width_points - self.margin_left_points - self.margin_right_points
- }
-
- fn printable_height(&self) -> f64 {
- self.page_height_points - self.margin_top_points - self.margin_bottom_points
- }
-
- fn selected_pages(&self, page_count: usize) -> Result<Vec<usize>, PdfError> {
- if self.page_ranges.is_empty() {
- return Ok((0..page_count).collect());
- }
- let mut pages = BTreeSet::new();
- for range in &self.page_ranges {
- if range.first >= page_count {
- continue;
- }
- let last = range.last.min(page_count.saturating_sub(1));
- pages.extend(range.first..=last);
- }
- if pages.is_empty() {
- return Err(PdfError::server("Page range exceeds page count"));
- }
- Ok(pages.into_iter().collect())
- }
}
fn finite_margin(value: Option<f64>, negative_message: &'static str) -> Result<f64, PdfError> {
@@ -220,141 +191,23 @@ fn page_range_syntax_error() -> PdfError {
PdfError::server("Page range syntax error")
}
-/// Wraps one full-document JPEG in a paginated PDF.
-///
-/// The raster is kept as one shared image XObject. Each output page clips and
-/// translates that image to expose the corresponding document slice, avoiding
-/// another decode/encode pass and keeping the result deterministic.
-pub(super) fn build_raster_pdf(
- jpeg: &[u8],
- image_width: u32,
- image_height: u32,
- options: &RasterPdfOptions,
-) -> Result<Vec<u8>, PdfError> {
- if jpeg.is_empty() || image_width == 0 || image_height == 0 {
- return Err(PdfError::server("Printing failed"));
- }
-
- let printable_width = options.printable_width();
- let printable_height = options.printable_height();
- let display_width = printable_width * options.scale;
- let display_height = display_width * f64::from(image_height) / f64::from(image_width);
- if !display_height.is_finite() || display_height <= 0.0 {
- return Err(PdfError::server("Printing failed"));
- }
- let page_count = (display_height / printable_height).ceil().max(1.0) as usize;
- if page_count > MAX_PAGE_COUNT {
- return Err(PdfError::server(format!(
- "Printing failed: document exceeds {MAX_PAGE_COUNT} pages"
- )));
- }
- let selected_pages = options.selected_pages(page_count)?;
-
- let page_object_ids = (0..selected_pages.len())
- .map(|index| 4 + index * 2)
- .collect::<Vec<_>>();
- let object_count = 3 + selected_pages.len() * 2;
- let mut objects = vec![Vec::new(); object_count + 1];
- objects[1] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec();
-
- let kids = page_object_ids
- .iter()
- .map(|id| format!("{id} 0 R"))
- .collect::<Vec<_>>()
- .join(" ");
- objects[2] = format!(
- "<< /Type /Pages /Kids [{kids}] /Count {} >>",
- selected_pages.len()
- )
- .into_bytes();
-
- let image_dictionary = format!(
- "<< /Type /XObject /Subtype /Image /Width {image_width} /Height {image_height} \
- /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length {} >>\nstream\n",
- jpeg.len()
- );
- let mut image_object = image_dictionary.into_bytes();
- image_object.extend_from_slice(jpeg);
- image_object.extend_from_slice(b"\nendstream");
- objects[3] = image_object;
-
- for (output_index, source_page) in selected_pages.iter().copied().enumerate() {
- let page_id = page_object_ids[output_index];
- let content_id = page_id + 1;
- objects[page_id] = format!(
- "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] \
- /Resources << /XObject << /Im0 3 0 R >> >> /Contents {content_id} 0 R >>",
- pdf_number(options.page_width_points),
- pdf_number(options.page_height_points),
- )
- .into_bytes();
-
- let clip_bottom = options.margin_bottom_points;
- let image_bottom = options.page_height_points - options.margin_top_points - display_height
- + source_page as f64 * printable_height;
- let content = format!(
- "q\n{} {} {} {} re W n\n{} 0 0 {} {} {} cm\n/Im0 Do\nQ\n",
- pdf_number(options.margin_left_points),
- pdf_number(clip_bottom),
- pdf_number(printable_width),
- pdf_number(printable_height),
- pdf_number(display_width),
- pdf_number(display_height),
- pdf_number(options.margin_left_points),
- pdf_number(image_bottom),
- );
- objects[content_id] = stream_object(content.as_bytes());
- }
-
- serialize_pdf(objects)
-}
-
-fn stream_object(bytes: &[u8]) -> Vec<u8> {
- let mut object = format!("<< /Length {} >>\nstream\n", bytes.len()).into_bytes();
- object.extend_from_slice(bytes);
- object.extend_from_slice(b"endstream");
- object
-}
-
-fn serialize_pdf(objects: Vec<Vec<u8>>) -> Result<Vec<u8>, PdfError> {
- let mut output = b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n".to_vec();
- let mut offsets = vec![0usize; objects.len()];
- for (id, object) in objects.iter().enumerate().skip(1) {
- if object.is_empty() {
- return Err(PdfError::server("Printing failed"));
+impl PrintPdfOptions {
+ pub(super) fn into_renderer_options(self) -> moli_core::page::RendererPdfOptions {
+ moli_core::page::RendererPdfOptions {
+ width: self.page_width_points,
+ height: self.page_height_points,
+ margin_top: self.margin_top_points,
+ margin_bottom: self.margin_bottom_points,
+ margin_left: self.margin_left_points,
+ margin_right: self.margin_right_points,
+ scale: self.scale,
+ page_ranges: self
+ .page_ranges
+ .into_iter()
+ .map(|range| range.first..=range.last)
+ .collect(),
}
- offsets[id] = output.len();
- let _ = writeln!(output, "{id} 0 obj");
- output.extend_from_slice(object);
- output.extend_from_slice(b"\nendobj\n");
- }
-
- let xref_offset = output.len();
- let _ = write!(output, "xref\n0 {}\n", objects.len());
- output.extend_from_slice(b"0000000000 65535 f \n");
- for offset in offsets.into_iter().skip(1) {
- let _ = writeln!(output, "{offset:010} 00000 n ");
- }
- let _ = write!(
- output,
- "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n",
- objects.len()
- );
- Ok(output)
-}
-
-fn pdf_number(value: f64) -> String {
- let mut value = format!("{value:.4}");
- while value.ends_with('0') {
- value.pop();
- }
- if value.ends_with('.') {
- value.pop();
}
- if value == "-0" {
- value = "0".to_owned();
- }
- value
}
#[cfg(test)]
@@ -362,6 +215,21 @@ mod tests {
use super::*;
use crate::automation::{AutomationContext, DevToolsPrintToPdfTransferMode, FrontendProtocol};
+ fn build_pdf(
+ snapshot: &moli_layout::PaintSnapshot,
+ options: &PrintPdfOptions,
+ ) -> Result<Vec<u8>, PdfError> {
+ moli_paint::pdf::pdf_snapshot(snapshot, &options.clone().into_renderer_options())
+ .map_err(|error| PdfError::server(error.to_string()))
+ }
+
+ fn snapshot(width: u32, height: u32) -> moli_layout::PaintSnapshot {
+ moli_layout::PaintSnapshot::new(
+ moli_layout::PaintViewport::new(width, height, 1.0),
+ moli_layout::PaintColor::WHITE,
+ )
+ }
+
fn command() -> DevToolsPrintToPdfCommand {
DevToolsPrintToPdfCommand {
context: AutomationContext {
@@ -394,15 +262,18 @@ mod tests {
command.margin_bottom = Some(0.0);
command.margin_left = Some(0.0);
command.margin_right = Some(0.0);
- let options = RasterPdfOptions::from_command(&command).unwrap();
- let pdf = build_raster_pdf(&[0xff, 0xd8, 0xff, 0xd9], 400, 900, &options).unwrap();
+ let options = PrintPdfOptions::from_command(&command).unwrap();
+ let pdf = build_pdf(&snapshot(400, 900), &options).unwrap();
let text = String::from_utf8_lossy(&pdf);
assert!(pdf.starts_with(b"%PDF-1.7"));
assert!(pdf.ends_with(b"%%EOF\n"));
assert!(text.contains("/Count 3"));
- assert_eq!(text.matches("/Type /Page ").count(), 3);
- assert_eq!(text.matches("/Subtype /Image").count(), 1);
+ assert_eq!(
+ lopdf::Document::load_mem(&pdf).unwrap().get_pages().len(),
+ 3
+ );
+ assert_eq!(text.matches("/Subtype /Image").count(), 0);
let xref_offset = text
.rsplit_once("startxref\n")
@@ -424,31 +295,43 @@ mod tests {
command.margin_left = Some(0.0);
command.margin_right = Some(0.0);
command.page_ranges = Some("3, 1-2,2".to_owned());
- let options = RasterPdfOptions::from_command(&command).unwrap();
- let pdf = build_raster_pdf(&[0xff, 0xd8, 0xff, 0xd9], 800, 2400, &options).unwrap();
- let text = String::from_utf8_lossy(&pdf);
-
- assert!(text.contains("/MediaBox [0 0 720 576]"));
- assert!(text.contains("/Count 3"));
+ let options = PrintPdfOptions::from_command(&command).unwrap();
+ let pdf = build_pdf(&snapshot(800, 2400), &options).unwrap();
+ let document = lopdf::Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 3);
+ for id in document.get_pages().values() {
+ let media_box = document
+ .get_dictionary(*id)
+ .unwrap()
+ .get(b"MediaBox")
+ .unwrap()
+ .as_array()
+ .unwrap();
+ let dimensions: Vec<_> = media_box
+ .iter()
+ .map(|value| value.as_float().unwrap())
+ .collect();
+ assert_eq!(dimensions, vec![0.0, 0.0, 720.0, 576.0]);
+ }
}
#[test]
fn validates_chromium_scale_and_page_range_errors() {
let mut invalid_scale = command();
invalid_scale.scale = Some(2.01);
- let error = RasterPdfOptions::from_command(&invalid_scale).unwrap_err();
+ let error = PrintPdfOptions::from_command(&invalid_scale).unwrap_err();
assert_eq!(error.code(), -32602);
assert_eq!(error.message(), "scale is outside of [0.1 - 2] range");
let mut invalid_range = command();
invalid_range.page_ranges = Some("4-2".to_owned());
- let error = RasterPdfOptions::from_command(&invalid_range).unwrap_err();
+ let error = PrintPdfOptions::from_command(&invalid_range).unwrap_err();
assert_eq!(error.code(), -32000);
assert_eq!(error.message(), "Page range is invalid (start > end)");
let mut syntax_error = command();
syntax_error.page_ranges = Some("1-a".to_owned());
- let error = RasterPdfOptions::from_command(&syntax_error).unwrap_err();
+ let error = PrintPdfOptions::from_command(&syntax_error).unwrap_err();
assert_eq!(error.message(), "Page range syntax error");
}
@@ -460,8 +343,8 @@ mod tests {
command.margin_bottom = Some(0.0);
command.margin_left = Some(0.0);
command.margin_right = Some(0.0);
- let options = RasterPdfOptions::from_command(&command).unwrap();
- let error = build_raster_pdf(&[0xff, 0xd8, 0xff, 0xd9], 800, 600, &options).unwrap_err();
+ let options = PrintPdfOptions::from_command(&command).unwrap();
+ let error = build_pdf(&snapshot(800, 600), &options).unwrap_err();
assert_eq!(error.message(), "Page range exceeds page count");
}
}
diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rs
index d2c7d3679..c94570f4c 100644
--- a/moli-protocol/src/domains/page/tests/capture.rs
+++ b/moli-protocol/src/domains/page/tests/capture.rs
@@ -650,6 +650,14 @@ async fn print_to_pdf_returns_base64_pdf_without_publishing_interactive_geometry
let pdf = screenshot_bytes(&take_response_by_id(&mut ctx, 1112));
assert!(pdf.starts_with(b"%PDF-1.7"));
assert!(pdf.ends_with(b"%%EOF\n"));
+ let document = lopdf::Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.extract_text(&[1]).unwrap().trim(), "pdf");
+ assert!(document.objects.values().any(|object| {
+ object
+ .as_dict()
+ .is_ok_and(|dict| dict.has(b"FontFile2") || dict.has(b"FontFile3"))
+ }));
+
// Printing a cold page must not publish its print-media geometry.
ctx.process_async(json!({
"id":1113,"method":"Runtime.evaluate","sessionId":"SID-PDF-BASE64",
@@ -1545,3 +1553,64 @@ async fn get_layout_metrics_targets_inactive_loaded_owner_without_activation() {
"inactive Page.getLayoutMetrics should not activate its browser context"
);
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn print_to_pdf_preserves_shaped_text_webfonts_and_selected_pages() {
+ let latin = BASE64_STANDARD.encode(include_bytes!(
+ "../../../../../moli-paint/tests/fixtures/moli-pdf.ttf"
+ ));
+ let cjk = BASE64_STANDARD.encode(include_bytes!(
+ "../../../../../moli-layout/tests/fixtures/moli-cjk.ttf"
+ ));
+ let html = format!(
+ r#"<!doctype html><meta charset="utf-8"><style>
+@font-face{{font-family:Latin;font-weight:400 900;src:url(data:font/ttf;base64,{latin})}}
+@font-face{{font-family:CJK;src:url(data:font/ttf;base64,{cjk})}}
+html,body{{margin:0}} body{{font:650 20px Latin,CJK;white-space:nowrap}}
+.first{{position:absolute;top:20px}} .second{{position:absolute;top:900px}}
+</style><div class=first>Font <span style="color:red">Text</span> 123 中文 office fi</div><div class=second>Second page</div>"#
+ );
+ let url = format!("data:text/html;base64,{}", BASE64_STANDARD.encode(html));
+ let mut ctx = TestContext::new_with_target_discovery_and_optional_resource_fetch_mask(
+ false,
+ moli_core::OptionalResourceFetchMask::FONT,
+ );
+ install_active_screenshot_page(
+ &mut ctx,
+ "BID-PDF-TEXT",
+ "TID-PDF-TEXT",
+ "SID-PDF-TEXT",
+ &url,
+ )
+ .await;
+ ctx.process_async(json!({"id": 1300,"method":"Emulation.setDeviceMetricsOverride","sessionId":"SID-PDF-TEXT","params":{"width":800,"height":300,"deviceScaleFactor":2,"mobile":false}})).await;
+ take_response_by_id(&mut ctx, 1300);
+ for (id, ranges, expected) in [
+ (1301, "", "Font Text 123 中文 office fi Second page"),
+ (1302, "2", "Second page"),
+ ] {
+ ctx.process_async(json!({"id":id,"method":"Page.printToPDF","sessionId":"SID-PDF-TEXT","params":{"paperWidth":4.0,"paperHeight":4.0,"marginTop":0,"marginBottom":0,"marginLeft":0,"marginRight":0,"pageRanges":ranges}})).await;
+ let pdf = screenshot_bytes(&take_response_by_id(&mut ctx, id));
+ let document = lopdf::Document::load_mem(&pdf).unwrap();
+ let pages: Vec<_> = document.get_pages().keys().copied().collect();
+ let text = document
+ .extract_text(&pages)
+ .unwrap()
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ");
+ assert_eq!(text, expected);
+ assert_eq!(pages.len(), if ranges.is_empty() { 2 } else { 1 });
+ assert!(
+ document
+ .objects
+ .values()
+ .any(|object| object.as_dict().is_ok_and(|dict| {
+ dict.get(b"BaseFont")
+ .and_then(lopdf::Object::as_name)
+ .is_ok_and(|name| String::from_utf8_lossy(name).contains("MoliPDF"))
+ })),
+ "the configured web font must actually be loaded and embedded"
+ );
+ }
+}
diff --git a/moli-protocol/src/lib.rs b/moli-protocol/src/lib.rs
index f93ae6645..e307a2660 100644
--- a/moli-protocol/src/lib.rs
+++ b/moli-protocol/src/lib.rs
@@ -42,7 +42,7 @@ pub use domains::activity::{
pub use domains::page::{
BackgroundNavigationCompletion, CompletedPageScreencastCapture,
PageScreencastCaptureCompletion, PageScreencastCaptureStart, PageScreencastRegistration,
- PageScreencastSubscriptionStatus, PendingPageScreencastCapture, build_default_raster_pdf,
+ PageScreencastSubscriptionStatus, PendingPageScreencastCapture,
};
pub use domains::runtime::{
CompletedDevToolsRuntimeCommandDispatch, DevToolsRuntimeCommandTaskStep,
diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml
index f460d6ed1..c7ece53cf 100644
--- a/moli-renderer-v8/Cargo.toml
+++ b/moli-renderer-v8/Cargo.toml
@@ -132,6 +132,7 @@ v8 = { version = "152.2.0", features = ["v8_enable_pointer_compression"] }
v8 = "152.2.0"
[dev-dependencies]
+lopdf = { version = "0.45.0", default-features = false }
fastrand = "2.3.0"
moli-fetch = { path = "../moli-fetch", features = ["test-support"] }
moli-parser = { path = "../moli-parser", features = ["test-support"] }
diff --git a/moli-renderer-v8/src/devtools/command/nested.rs b/moli-renderer-v8/src/devtools/command/nested.rs
index 302776468..7e73d73da 100644
--- a/moli-renderer-v8/src/devtools/command/nested.rs
+++ b/moli-renderer-v8/src/devtools/command/nested.rs
@@ -157,6 +157,7 @@ impl RendererPageCommand {
| Self::ResetNavigationHistory
| Self::SetFileInputFilesForBackendNodeId { .. }
| Self::RenderPageDump { .. }
+ | Self::PrintToPdf(..)
| Self::CaptureScreenshot(..)
| Self::SearchResourceByLines(..)
| Self::ContinuePendingSubresourceFetch { .. }
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index 1f07d5e32..567ff222f 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -298,16 +298,16 @@ pub use runtime::{
RendererPageReplacementError, RendererPageReplacementFailureDisposition,
RendererPageReplacementReservationRequest, RendererPageReplacementTarget, RendererPageReply,
RendererPageReservationToken, RendererPageState, RendererPageStateRevision,
- RendererPageTestingHandle, RendererPageView, RendererPendingAuxiliaryPage,
+ RendererPageTestingHandle, RendererPageView, RendererPdfOptions, RendererPendingAuxiliaryPage,
RendererPendingDownloadActivation, RendererPendingDownloadResponse,
RendererPendingFileChooserActivation, RendererPendingJavaScriptDialog,
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererPerformanceMetricSnapshot, RendererPointerEventProperties,
RendererPopupActivationSource, RendererPopupDisposition,
- RendererPreparedDocumentCommitConfiguration, RendererProtocolObservation,
- RendererReservedServiceWorkerClient, RendererResourceContentBody,
- RendererResourceSearchRequest, RendererResourceTextSearchOutcome,
+ RendererPreparedDocumentCommitConfiguration, RendererPrintToPdfReply,
+ RendererPrintToPdfRequest, RendererProtocolObservation, RendererReservedServiceWorkerClient,
+ RendererResourceContentBody, RendererResourceSearchRequest, RendererResourceTextSearchOutcome,
RendererRuntimeCommandCausalIdentity, RendererRuntimeCommandOutput,
RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage, RendererRuntimeHeapUsage,
RendererRuntimeInspectorAsyncCompletion, RendererRuntimeInspectorIoCommandClaim,
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index d65ef9878..f47fa5e43 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -369,30 +369,30 @@ pub use self::page_surface::{
RendererNavigationInitiator, RendererPageCommand, RendererPageCommandPostResponseContinuation,
RendererPageCookieFacadeSnapshotReply, RendererPageCreationDiagnostics,
RendererPageDiagnosticsSnapshot, RendererPageDumpFormat, RendererPageDumpOptions,
- RendererPageDumpStripOptions, RendererPageReply, RendererPageView,
+ RendererPageDumpStripOptions, RendererPageReply, RendererPageView, RendererPdfOptions,
RendererPendingDownloadActivation, RendererPendingDownloadResponse,
RendererPendingFileChooserActivation, RendererPendingJavaScriptDialog,
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererPerformanceMetricSnapshot, RendererPointerEventProperties,
- RendererPopupActivationSource, RendererPopupDisposition, RendererResourceTextSearchOutcome,
- RendererRuntimeCommandOutput, RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage,
- RendererRuntimeHeapUsage, RendererRuntimeInspectorAsyncCompletion,
- RendererRuntimeInspectorMessage, RendererRuntimeInspectorMessageBatch,
- RendererRuntimeInspectorProtocolMessage, RendererRuntimeInspectorProtocolMessageValueMut,
- RendererRuntimeInspectorResponseChannel, RendererRuntimeInspectorResponseSender,
- RendererRuntimeObservableSourceItem, RendererRuntimeObservableSourceSummary,
- RendererRuntimeRealmInfo, RendererRuntimeRemoteObject, RendererRuntimeRemoteObjectResolution,
- RendererScriptExecutionMemoryDiagnostics, RendererScriptSourceMemoryDiagnostics,
- RendererScrollIntoViewResult, RendererServiceWorkerConsoleMessage,
- RendererServiceWorkerExceptionMessage, RendererServiceWorkerFetchDiagnostic,
- RendererServiceWorkerFetchDiagnosticResult, RendererServiceWorkerTargetEvent,
- RendererServiceWorkerTargetInfo, RendererServiceWorkerVersionStatus,
- RendererSetDocumentContentResult, RendererSharedWorkerConsoleMessage,
- RendererSharedWorkerTargetEvent, RendererSharedWorkerTargetInfo, RendererStyleSheetHeader,
- RendererStyleSheetInventoryUpdate, RendererStyleSheetPayload, RendererSyntheticResponseBody,
- RendererTextSearchMatch, RendererTouchPoint, RendererWindowDocumentSource,
- RuntimeConsoleMessageSnapshot,
+ RendererPopupActivationSource, RendererPopupDisposition, RendererPrintToPdfReply,
+ RendererPrintToPdfRequest, RendererResourceTextSearchOutcome, RendererRuntimeCommandOutput,
+ RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage, RendererRuntimeHeapUsage,
+ RendererRuntimeInspectorAsyncCompletion, RendererRuntimeInspectorMessage,
+ RendererRuntimeInspectorMessageBatch, RendererRuntimeInspectorProtocolMessage,
+ RendererRuntimeInspectorProtocolMessageValueMut, RendererRuntimeInspectorResponseChannel,
+ RendererRuntimeInspectorResponseSender, RendererRuntimeObservableSourceItem,
+ RendererRuntimeObservableSourceSummary, RendererRuntimeRealmInfo, RendererRuntimeRemoteObject,
+ RendererRuntimeRemoteObjectResolution, RendererScriptExecutionMemoryDiagnostics,
+ RendererScriptSourceMemoryDiagnostics, RendererScrollIntoViewResult,
+ RendererServiceWorkerConsoleMessage, RendererServiceWorkerExceptionMessage,
+ RendererServiceWorkerFetchDiagnostic, RendererServiceWorkerFetchDiagnosticResult,
+ RendererServiceWorkerTargetEvent, RendererServiceWorkerTargetInfo,
+ RendererServiceWorkerVersionStatus, RendererSetDocumentContentResult,
+ RendererSharedWorkerConsoleMessage, RendererSharedWorkerTargetEvent,
+ RendererSharedWorkerTargetInfo, RendererStyleSheetHeader, RendererStyleSheetInventoryUpdate,
+ RendererStyleSheetPayload, RendererSyntheticResponseBody, RendererTextSearchMatch,
+ RendererTouchPoint, RendererWindowDocumentSource, RuntimeConsoleMessageSnapshot,
};
pub(crate) use self::page_surface::{
RendererCommandTurnOutputRecorder, RendererDevToolsSessionOutputHost,
diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rs
index 956207395..2be78f73b 100644
--- a/moli-renderer-v8/src/runtime/page_commands.rs
+++ b/moli-renderer-v8/src/runtime/page_commands.rs
@@ -838,6 +838,9 @@ impl PageVm {
self.vm_mut().publish_layout()?;
Ok(RendererPageReply::Unit)
}
+ RendererPageCommand::PrintToPdf(request) => self
+ .print_to_pdf(request)
+ .map(RendererPageReply::PrintToPdf),
RendererPageCommand::CaptureScreenshot(request) => self
.capture_screenshot(request)
.map(RendererPageReply::CaptureScreenshot),
diff --git a/moli-renderer-v8/src/runtime/page_screenshot.rs b/moli-renderer-v8/src/runtime/page_screenshot.rs
index 4d9c603f5..f82df8de7 100644
--- a/moli-renderer-v8/src/runtime/page_screenshot.rs
+++ b/moli-renderer-v8/src/runtime/page_screenshot.rs
@@ -188,6 +188,51 @@ impl RendererCaptureScreenshotRequest {
}
impl PageVm {
+ /// Projects print media and encodes PDF without allocating a full-document
+ /// bitmap or publishing interactive screen geometry. Both output clients
+ /// use this lifecycle, including restoration before any encoding error.
+ pub(super) fn print_to_pdf(
+ &mut self,
+ request: super::RendererPrintToPdfRequest,
+ ) -> anyhow::Result<super::RendererPrintToPdfReply> {
+ use super::RendererPrintToPdfReply as Reply;
+ self.flush_page_action_window(moli_action_window::ActionBarrier::Explicit)?;
+ if self.layout_configuration.policy == LayoutPolicy::Mock {
+ return Ok(Reply::LayoutDisabled);
+ }
+ let previous = self.document_settings.emulated_media.clone();
+ let restore = previous.media.is_none();
+ if restore {
+ let mut print = previous.clone();
+ print.media = Some("print".to_owned());
+ self.set_emulated_media(&print)?;
+ }
+ let surface = self.document_settings.viewport_surface.unwrap_or_default();
+ let viewport = PaintViewport::new(
+ surface.inner_width,
+ surface.inner_height,
+ surface.device_pixel_ratio as f32,
+ );
+ let result = self.vm_mut().paint_layout_snapshot_with_capture(
+ viewport,
+ moli_layout::LayoutFlushReason::Print,
+ PaintCaptureRequest {
+ include_backgrounds: request.print_background,
+ ..PaintCaptureRequest::print_document()
+ },
+ );
+ if restore {
+ self.set_emulated_media(&previous)?;
+ }
+ Ok(match result? {
+ Some(snapshot) => match moli_paint::pdf::pdf_snapshot(&snapshot, &request.options) {
+ Ok(bytes) => Reply::Printed(bytes),
+ Err(error) => Reply::Failed(error.to_string()),
+ },
+ None => Reply::NoDocument,
+ })
+ }
+
/// Captures an explicit screenshot or print raster. These demands always
/// execute a fresh paint pass and never carry screencast state.
pub(super) fn capture_screenshot(
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 2e3924a0d..ad391b67c 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -5120,6 +5120,7 @@ pub enum RendererPageCommand {
SerializeDocument,
LayoutMetrics,
PublishLayout,
+ PrintToPdf(RendererPrintToPdfRequest),
CaptureScreenshot(RendererCaptureScreenshotRequest),
CaptureScreencastFrame(RendererCaptureScreencastFrameRequest),
BlobBytesForUuid {
@@ -5740,6 +5741,7 @@ impl RendererPageCommand {
Self::SerializeDocument => Some("SerializeDocument"),
Self::LayoutMetrics => Some("LayoutMetrics"),
Self::PublishLayout => Some("PublishLayout"),
+ Self::PrintToPdf(_) => Some("PrintToPdf"),
Self::CaptureScreenshot(_) => Some("CaptureScreenshot"),
Self::CaptureScreencastFrame(_) => Some("CaptureScreencastFrame"),
Self::ScrollNodeIntoViewIfNeeded { .. } => Some("ScrollNodeIntoViewIfNeeded"),
@@ -6057,6 +6059,22 @@ pub enum RendererCaptureScreencastFrameReply {
NoDocument,
}
+pub use moli_paint::pdf::PdfOptions as RendererPdfOptions;
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RendererPrintToPdfRequest {
+ pub options: RendererPdfOptions,
+ pub print_background: bool,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum RendererPrintToPdfReply {
+ Printed(Vec<u8>),
+ Failed(String),
+ LayoutDisabled,
+ NoDocument,
+}
+
pub enum RendererPageReply {
WebMcp(std::result::Result<Option<u64>, moli_page_types::RendererWebMcpError>),
NativeCommandReady(Box<RendererNativeCommandReadyResponse>),
@@ -6139,6 +6157,7 @@ pub enum RendererPageReply {
Usize(usize),
CookieFacadeSnapshot(Box<RendererPageCookieFacadeSnapshotReply>),
LayoutMetrics(RendererLayoutMetrics),
+ PrintToPdf(RendererPrintToPdfReply),
CaptureScreenshot(RendererCaptureScreenshotReply),
CaptureScreencastFrame(RendererCaptureScreencastFrameReply),
Unit,
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs
index 75a254744..ad696a1f8 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs
@@ -1,8 +1,53 @@
use super::*;
use crate::runtime::{
- RendererCaptureScreenshotReply, RendererCaptureScreenshotRequest, RendererScreenshotPurpose,
+ RendererCaptureScreenshotReply, RendererCaptureScreenshotRequest, RendererPrintToPdfReply,
+ RendererPrintToPdfRequest, RendererScreenshotPurpose,
};
+#[tokio::test(flavor = "current_thread")]
+async fn native_pdf_restores_media_on_success_and_failure_and_keeps_iframe_text() {
+ run_page_vm_async_test(async move {
+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader, Vec::new(), Url::parse("https://example.com/native-print.html")?,
+ );
+ page_vm.vm_mut().eval(r#"
+document.head.innerHTML = `<style>
+.print { display:none } @media print { .screen { display:none } .print { display:block } }
+</style>`;
+document.body.innerHTML = '<p class=screen>Screen parent</p><p class=print>Print parent</p><iframe id=child></iframe>';
+child.contentDocument.body.innerHTML = '<p>Iframe text</p>';
+'installed'
+"#)?;
+ let extract = |reply| -> anyhow::Result<String> {
+ let RendererPrintToPdfReply::Printed(bytes) = reply else { anyhow::bail!("expected PDF, got {reply:?}"); };
+ let doc = lopdf::Document::load_mem(&bytes)?;
+ Ok(doc.extract_text(&doc.get_pages().keys().copied().collect::<Vec<_>>())?
+ .split_whitespace().collect::<Vec<_>>().join(" "))
+ };
+ let cold = page_vm.vm().layout_snapshot_cache_observability_for_test().2;
+ assert_eq!(extract(page_vm.print_to_pdf(Default::default())?)?, "Print parent Iframe text");
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test().2, cold);
+ assert_eq!(page_vm.vm_mut().eval("matchMedia('print').matches")?, "false");
+
+ page_vm.capture_screenshot(RendererCaptureScreenshotRequest::viewport_png())?;
+ let warm = page_vm.vm().layout_snapshot_cache_observability_for_test().2;
+ let mut invalid = RendererPrintToPdfRequest::default();
+ invalid.options.width = 0.0;
+ assert!(matches!(page_vm.print_to_pdf(invalid)?, RendererPrintToPdfReply::Failed(_)));
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test().2, warm);
+ assert_eq!(page_vm.vm_mut().eval("matchMedia('print').matches")?, "false");
+
+ let mut media = page_vm.document_settings.emulated_media.clone();
+ media.media = Some("screen".to_owned());
+ page_vm.set_emulated_media(&media)?;
+ assert_eq!(extract(page_vm.print_to_pdf(Default::default())?)?, "Screen parent Iframe text");
+ assert_eq!(page_vm.document_settings.emulated_media, media);
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test().2, warm);
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("native printing preserves media and interactive state");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn print_capture_preserves_published_geometry_frame_viewports_and_mouse_targets() {
run_page_vm_async_test(async move {
diff --git a/moli/Cargo.toml b/moli/Cargo.toml
index 7a30cb990..6aef9a8c5 100644
--- a/moli/Cargo.toml
+++ b/moli/Cargo.toml
@@ -43,6 +43,7 @@ tikv-jemalloc-sys = { version = "0.7.1", optional = true, default-features = fal
tikv-jemallocator = { version = "0.7.0", optional = true, default-features = false, features = ["override_allocator_on_supported_platforms"] }
[dev-dependencies]
+lopdf = { version = "0.45.0", default-features = false }
libc = "0.2"
moli-test-support = { path = "../moli-test-support" }
strip-ansi-escapes = "0.2.1"
diff --git a/moli/src/fetch_dump/raster.rs b/moli/src/fetch_dump/raster.rs
index 41429f5b4..dcee7558d 100644
--- a/moli/src/fetch_dump/raster.rs
+++ b/moli/src/fetch_dump/raster.rs
@@ -1,13 +1,11 @@
use anyhow::{Context, Result, bail};
use moli_core::page::{
Page, RendererCaptureScreenshotReply, RendererCaptureScreenshotRequest,
- RendererScreenshotFormat, RendererScreenshotPurpose, RendererScreenshotRegion,
+ RendererPrintToPdfReply, RendererScreenshotRegion,
};
struct CapturedRaster {
mime_type: String,
- width: u32,
- height: u32,
bytes: Vec<u8>,
}
@@ -29,31 +27,23 @@ pub(super) async fn render_screenshot(
}
pub(super) async fn render_pdf(page: &mut Page) -> Result<Vec<u8>> {
- let image = capture_page_raster(
- page,
- RendererCaptureScreenshotRequest {
- base_background_color: [255; 4],
- purpose: RendererScreenshotPurpose::Print {
- print_background: false,
- },
- format: RendererScreenshotFormat::Jpeg,
- quality: 90,
- region: RendererScreenshotRegion::FullDocument,
- optimize_for_speed: false,
- max_width: None,
- max_height: None,
- },
- "pdf",
- )
- .await?;
- if image.mime_type != "image/jpeg" {
- bail!(
- "PDF renderer returned `{}` instead of JPEG",
- image.mime_type
- );
+ let pending = page
+ .start_print_to_pdf(Default::default())
+ .context("failed to start --dump pdf capture")?;
+ let completion = pending
+ .wait()
+ .await
+ .context("failed to complete --dump pdf capture")?;
+ match page.finish_print_to_pdf(completion)? {
+ RendererPrintToPdfReply::Printed(bytes) => Ok(bytes),
+ RendererPrintToPdfReply::Failed(error) => bail!("{error}"),
+ RendererPrintToPdfReply::LayoutDisabled => {
+ bail!("--dump pdf requires --layout or MOLI_LAYOUT=true")
+ }
+ RendererPrintToPdfReply::NoDocument => {
+ bail!("--dump pdf requires a loaded HTML document")
+ }
}
- moli_protocol::build_default_raster_pdf(&image.bytes, image.width, image.height)
- .context("failed to encode PDF output")
}
async fn capture_page_raster(
@@ -71,8 +61,6 @@ async fn capture_page_raster(
match page.finish_capture_screenshot(completion)? {
RendererCaptureScreenshotReply::Captured(image) => Ok(CapturedRaster {
mime_type: image.mime_type,
- width: image.width,
- height: image.height,
bytes: image.bytes.to_vec(),
}),
RendererCaptureScreenshotReply::LayoutDisabled => {
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs
index 4e1662434..d1e058993 100644
--- a/moli/tests/fetch_cli.rs
+++ b/moli/tests/fetch_cli.rs
@@ -1123,7 +1123,11 @@ fn cli_dump_full_screenshot_captures_tall_page_without_prior_layout() -> Result<
#[test]
fn cli_dump_pdf_writes_pdf_bytes() -> Result<()> {
- let output = run_fetch_cli_with_dump_and_args("about:blank", "pdf", &["--layout"])?;
+ let url = format!(
+ "data:text/html;base64,{}",
+ BASE64_STANDARD.encode("<!doctype html><p>Font Text 123</p>")
+ );
+ let output = run_fetch_cli_with_dump_and_args(&url, "pdf", &["--layout"])?;
assert!(
output.status.success(),
"moli fetch failed: stdout_bytes={}\nstderr={}",
@@ -1131,12 +1135,9 @@ fn cli_dump_pdf_writes_pdf_bytes() -> Result<()> {
String::from_utf8_lossy(&output.stderr)
);
assert!(output.stdout.starts_with(b"%PDF-1.7\n"));
- assert!(
- output
- .stdout
- .windows(b"/Type /Pages".len())
- .any(|window| window == b"/Type /Pages")
- );
+ let document = lopdf::Document::load_mem(&output.stdout)?;
+ assert_eq!(document.get_pages().len(), 1);
+ assert_eq!(document.extract_text(&[1])?.trim(), "Font Text 123");
assert!(output.stdout.ends_with(b"%%EOF\n"));
Ok(())
}
diff --git a/scripts/check-native-pdf.py b/scripts/check-native-pdf.py
new file mode 100644
index 000000000..28de854b9
--- /dev/null
+++ b/scripts/check-native-pdf.py
@@ -0,0 +1,122 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["pymupdf==1.28.2"]
+# ///
+"""Exercise the real CLI and a PDF reader, including ActualText and Type3 glyphs.
+
+Run after building Moli:
+ uv run scripts/check-native-pdf.py --moli target/debug/moli
+Unlike lopdf's basic extractor, MuPDF interprets ActualText, reversed text and
+colored Type3 glyphs. Keep these reader checks separate from the Rust structural
+and plain-text regressions. Artifacts and observed process costs are retained.
+"""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+import subprocess
+import time
+
+import pymupdf
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def data_url(data, media_type):
+ return f"data:{media_type};base64," + base64.b64encode(data).decode()
+
+
+def capture(binary, output, name, html):
+ path = output / f"{name}.pdf"
+ started = time.perf_counter()
+ peak_kib = 0
+ with path.open("wb") as target:
+ process = subprocess.Popen(
+ [str(binary), "fetch", "--font", "--layout", "--wait-until", "load",
+ "--log-level", "error", "--http-no-proxy", "*", "--dump", "pdf",
+ data_url(html.encode(), "text/html")],
+ stdout=target, stderr=subprocess.PIPE,
+ )
+ while process.poll() is None:
+ if time.perf_counter() - started > 120:
+ process.kill()
+ process.communicate()
+ raise TimeoutError(f"{name} exceeded 120 seconds")
+ try:
+ for line in Path(f"/proc/{process.pid}/status").read_text().splitlines():
+ if line.startswith("VmHWM:"):
+ peak_kib = max(peak_kib, int(line.split()[1]))
+ except FileNotFoundError:
+ pass
+ time.sleep(0.005)
+ stderr = process.communicate()[1].decode(errors="replace")
+ if process.returncode:
+ raise RuntimeError(f"{name} failed: {stderr}")
+ seconds = time.perf_counter() - started
+ document = pymupdf.open(path)
+ text = " ".join(" ".join(page.get_text().split()) for page in document)
+ (output / f"{name}.txt").write_text(text)
+ document[0].get_pixmap(matrix=pymupdf.Matrix(1.5, 1.5)).save(output / f"{name}.png")
+ info = {"pages": len(document), "pdf_bytes": path.stat().st_size,
+ "seconds": round(seconds, 4), "peak_rss_kib_sampled": peak_kib,
+ "fonts": sorted({font[3] for page in document for font in page.get_fonts()}),
+ "image_count": sum(len(page.get_images()) for page in document)}
+ return text, info
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--moli", type=Path, default=ROOT / "target/debug/moli")
+ parser.add_argument("--output-dir", type=Path, default=ROOT / "target/native-pdf-check")
+ args = parser.parse_args()
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+ font = data_url((ROOT / "moli-paint/tests/fixtures/moli-pdf.ttf").read_bytes(), "font/ttf")
+ cjk = data_url((ROOT / "moli-layout/tests/fixtures/moli-cjk.ttf").read_bytes(), "font/ttf")
+ style = f"""<meta charset=utf-8><style>
+@font-face{{font-family:PDFTest;src:url({font});font-weight:400 900}}
+@font-face{{font-family:CJK;src:url({cjk})}}
+body{{font:20px PDFTest,CJK;margin:24px}} p{{margin:16px 0}}
+</style>"""
+ results = {}
+ text, results["minimal"] = capture(args.moli.resolve(), args.output_dir, "minimal",
+ style + "<h1>Font Text 123</h1>")
+ assert text == "Font Text 123", text
+ assert results["minimal"]["image_count"] == 0
+ assert any("+MoliPDFTest" in font for font in results["minimal"]["fonts"])
+
+ expected = ["Font Text 123 中文", "office fi ffi á", "Second page a", "abc אבג xyz",
+ "Color ★", "Weight 650", "Italic"]
+ html = style + """<p>Font Text 123 中文</p><p>office fi ffi á</p>
+<p>Second page a</p><p>abc אבג xyz</p><p>Color ★</p>
+<p style="font-weight:650">Weight 650</p><p style="font-style:italic">Italic</p>"""
+ text, results["shaping"] = capture(args.moli.resolve(), args.output_dir, "shaping", html)
+ assert text == " ".join(expected), text
+
+ html = style + """<p style="opacity:.65">Opacity text</p>
+<p style="text-shadow:2px 2px 2px red">Shadow text once</p>
+<p style="filter:blur(.3px)">Filtered text once</p>
+<p style="opacity:0">Hidden opacity</p>
+<p style="mask-image:linear-gradient(transparent,transparent)">Hidden mask</p>"""
+ text, results["effects"] = capture(args.moli.resolve(), args.output_dir, "effects", html)
+ for phrase in ["Opacity text", "Shadow text once", "Filtered text once"]:
+ assert text.count(phrase) == 1, text
+ assert "Hidden" not in text, text
+
+ # Exceeds the full-document screenshot CSS dimension limit. There is no
+ # full-document pixel allocation in this path, even at the default viewport.
+ html = style + '<main style="height:200100px">' + "".join(
+ f'<p style="position:absolute;top:{i * 700}px">Row {i:03}</p>' for i in range(286)
+ ) + "</main>"
+ text, results["long_document"] = capture(args.moli.resolve(), args.output_dir, "long-document", html)
+ assert text == " ".join(f"Row {i:03}" for i in range(286)), text
+ assert results["long_document"]["pages"] > 1
+ assert results["long_document"]["image_count"] == 0
+ report = {"binary": str(args.moli.resolve()), "binary_bytes": args.moli.stat().st_size,
+ "reader": pymupdf.version[0], "cases": results}
+ (args.output_dir / "results.json").write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps(report, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/generate-pdf-test-font.py b/scripts/generate-pdf-test-font.py
new file mode 100644
index 000000000..1862205c8
--- /dev/null
+++ b/scripts/generate-pdf-test-font.py
@@ -0,0 +1,73 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["fonttools==4.59.0"]
+# ///
+"""Derive an original variable/ligature PDF fixture from Moli's generated Ahem font."""
+import copy
+from pathlib import Path
+
+from fontTools.feaLib.builder import addOpenTypeFeaturesFromString
+from fontTools.colorLib.builder import buildCOLR, buildCPAL
+from fontTools.pens.ttGlyphPen import TTGlyphPen
+from fontTools.ttLib import TTFont, newTable
+from fontTools.ttLib.tables._f_v_a_r import Axis
+from fontTools.ttLib.tables.TupleVariation import TupleVariation
+
+root = Path(__file__).resolve().parents[1]
+font = TTFont(root / "moli-layout/tests/fixtures/moli-ahem.ttf", recalcTimestamp=False)
+# Distinct glyphs exercise multi-character ToUnicode mappings without relying
+# on installed fonts or copying third-party typeface data.
+for name, width in [("fi", 1200), ("ffi", 1800)]:
+ glyph = copy.deepcopy(font["glyf"]["uni0066"])
+ glyph.coordinates = type(glyph.coordinates)((int(x * width / 600), y) for x, y in glyph.coordinates)
+ font["glyf"][name] = glyph
+ font["hmtx"].metrics[name] = (width, 0)
+added = ["fi", "ffi"]
+for codepoint in [0x301, 0x5D0, 0x5D1, 0x5D2, 0x2605]:
+ name = f"uni{codepoint:04X}"
+ font["glyf"][name] = copy.deepcopy(font["glyf"]["uni0066"])
+ font["hmtx"].metrics[name] = (600, 0)
+ added.append(name)
+ for table in font["cmap"].tables:
+ if table.isUnicode():
+ table.cmap[codepoint] = name
+pen = TTGlyphPen(None)
+pen.moveTo((0, 900))
+pen.lineTo((200, 1100))
+pen.lineTo((300, 1100))
+pen.lineTo((100, 900))
+pen.closePath()
+font["glyf"]["uni0301"] = pen.glyph()
+font["hmtx"].metrics["uni0301"] = (0, 0)
+font.setGlyphOrder(list(dict.fromkeys(font.getGlyphOrder() + added)))
+addOpenTypeFeaturesFromString(font, """
+feature liga { sub uni0066 uni0066 uni0069 by ffi; sub uni0066 uni0069 by fi; } liga;
+markClass uni0301 <anchor 100 900> @TOP;
+feature mark { pos base uni0061 <anchor 300 800> mark @TOP; } mark;
+""")
+font["COLR"] = buildCOLR({"uni2605": [("uni0066", 0), ("uni0301", 1)]}, glyphMap=font.getReverseGlyphMap())
+font["CPAL"] = buildCPAL([[(1.0, 0.2, 0.0, 1.0), (0.0, 0.3, 1.0, 1.0)]])
+font["fvar"] = newTable("fvar")
+axis = Axis()
+axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue = "wght", 400, 400, 900
+axis.flags, axis.axisNameID = 0, font["name"].addName("Weight")
+font["fvar"].axes = [axis]
+font["fvar"].instances = []
+font["avar"] = newTable("avar")
+font["avar"].segments = {"wght": {-1.0: -1.0, 0.0: 0.0, 0.5: 0.75, 1.0: 1.0}}
+font["gvar"] = newTable("gvar")
+font["gvar"].variations = {}
+for name in font.getGlyphOrder():
+ glyph = font["glyf"][name]
+ if glyph.numberOfContours > 0:
+ # Widen the ink, but leave the advance unchanged. This distinguishes
+ # correct font instancing from simply stretching positioned text.
+ deltas = [(150 if x > 0 else 0, 0) for x, _ in glyph.coordinates]
+ font["gvar"].variations[name] = [TupleVariation({"wght": (0.0, 1.0, 1.0)}, deltas + [(0, 0)] * 4)]
+ else:
+ font["gvar"].variations[name] = []
+for record in list(font["name"].names):
+ value = {1: "Moli PDF Test", 4: "Moli PDF Test", 6: "MoliPDFTest"}.get(record.nameID)
+ if value is not None:
+ font["name"].setName(value, record.nameID, record.platformID, record.platEncID, record.langID)
+font.save(root / "moli-paint/tests/fixtures/moli-pdf.ttf")