mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-19 08:50:58 +01:00
* export: write RTF through craft-rtf's full writer, from the word model The pages are mapped onto a craft_wordmodel::Document (as_word.rs, the mapping the DOCX export will share), and craft_rtf::doc::export writes it. Over the small writer this keeps, in RTF: - pictures, inline (the engine no longer leaves them out for RTF); - each page's size, as a section per page (blank pages kept); - Heading 1 and 2 styles; - the title; - hard line breaks inside a paragraph or cell (storytold/pdfcraft#4723). It also fixes two bugs: \cellx was the absolute page x, so every column edge sat one left margin too far right, and tables that touched became one (NIST CSF 2.0 came out with 28 tables instead of 68). craft-rtf, craft-wordmodel, craft-docx and craft-mime are pinned together at one craft-libs commit: doc::export takes its own revision's Document. * export: pin craft-libs main with push_text, the header-row fix and the RTF generator name craft-rtf, craft-wordmodel, craft-docx and craft-mime move to craft-libs b8eaa8e2, which has storytold/craft-libs#1946, #1947 and #1950. The mapping appends through Paragraph::push_text/push_object, tables keep the default look, and the RTF names PdfCraft as its generator. * export: write Word through craft-docx, from the shared word model as_docx.rs no longer writes WordprocessingML itself: as_word::word_doc maps the pages onto a craft_wordmodel::Document and craft_docx::write writes it. The decisions stay the same: a page with rotated text or overlapping text keeps its layout as positioned text boxes and pictures (watermark-sized text behind, pictures over it, other text on top), the other pages flow, each page is a section of its own size, a shared page colour is the document's, the PDF's language goes in the slot Word keeps for its script, and the media limits are unchanged. Over the hand-written package this gains: - a VML fallback for every text box, so Word 2007 opens positioned pages; - rotated text as a turned text box Word draws as a line; - the body font named (Arial), with a font table saying it is a sans; - PdfCraft as the application in docProps/app.xml; - a picture drawn many times stored once. The tests that matched XML read the package back through craft-docx. * parity: the Word export through craft-docx, checked in Word 16, Word 2007 and LibreOffice * chore: update Cargo.lock after rebasing #7592 --------- Co-authored-by: kiwi4boy <kiwi4boy@gmail.com>
This commit is contained in:
1 parent
56f19a32c0
commit
d03b99ea54
12 files changed
+1049
-598
No files matched your search
Generated
+148
-10
@@ -1190,6 +1190,11 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
@@ -1211,7 +1216,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f29e82f1a7a009e68312bd2e84adab72be23344d#f29e82f1a7a009e68312bd2e84adab72be23344d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
@@ -1226,12 +1231,53 @@ name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-drawingml",
|
||||
"craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-offcrypto",
|
||||
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"log",
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"image",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
"image",
|
||||
"log",
|
||||
]
|
||||
@@ -1314,9 +1360,18 @@ name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
"craft-html",
|
||||
"craft-wordmodel",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1341,23 +1396,62 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f29e82f1a7a009e68312bd2e84adab72be23344d#f29e82f1a7a009e68312bd2e84adab72be23344d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"craft-cfb",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-zip",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1450,10 +1544,14 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f29e82f1a7a009e68312bd2e84adab72be23344d#f29e82f1a7a009e68312bd2e84adab72be23344d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-metafile",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"encoding_rs",
|
||||
"image",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1552,13 +1650,27 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
"craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1593,6 +1705,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1622,6 +1744,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
@@ -2759,9 +2891,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4698,8 +4832,10 @@ version = "0.21.1"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-docx",
|
||||
"craft-image-codecs",
|
||||
"craft-prc",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"flate2",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-engine",
|
||||
@@ -4856,12 +4992,14 @@ dependencies = [
|
||||
name = "pdfcraft-export"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"craft-docx",
|
||||
"craft-markdown",
|
||||
"craft-mime",
|
||||
"craft-opc",
|
||||
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-rtf",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-zip",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"flate2",
|
||||
]
|
||||
|
||||
|
||||
+6
-5
@@ -36,17 +36,18 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e2dc681a3", features = ["egui"] }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "8e03cd016d42032b867fef6bad86bc69bf2c1920", features = ["cos", "crypt", "filters"] }
|
||||
# The writer the RTF export maps onto (storytold/craft-libs#793), at storytold/craft-libs#1467:
|
||||
# its font and colour lookups take constant time, as PdfCraft's own writer did.
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f29e82f1a7a009e68312bd2e84adab72be23344d" }
|
||||
# The writers the Word and RTF exports map onto (storytold/craft-libs#793). craft-rtf, craft-wordmodel and
|
||||
# craft-docx move together: craft_rtf::doc::export takes its own revision's Document.
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" }
|
||||
# Shared Base64 encoder; use the existing RTF revision to reuse its codepage dependency.
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f29e82f1a7a009e68312bd2e84adab72be23344d" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" }
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
|
||||
|
||||
@@ -31,6 +31,9 @@ mcp = ["dep:base64"]
|
||||
# Synthetic printer profiles for the app-managed print colour tests.
|
||||
craft-cms = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
# Word exports read back as Word reads them.
|
||||
craft-docx = { workspace = true }
|
||||
craft-wordmodel = { workspace = true }
|
||||
pdfcraft-fonts = { workspace = true }
|
||||
flate2.workspace = true
|
||||
pdfcraft-model = { workspace = true }
|
||||
|
||||
@@ -10128,29 +10128,37 @@ BT /F1 11 Tf 20 20 Td (Total due: 150.00) Tj ET";
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "invoice.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "doc_export_office", json!({ "doc": doc, "path": "invoice.docx" }));
|
||||
// Inspect the actual package emitted by the tool, not an intermediate page model.
|
||||
let zip = std::fs::read(dir.join("invoice.docx")).unwrap();
|
||||
let mut at = 0;
|
||||
let mut xml = String::new();
|
||||
while zip[at..].starts_with(b"PK\x03\x04") {
|
||||
let size = u32::from_le_bytes(zip[at + 18..at + 22].try_into().unwrap()) as usize;
|
||||
let len = u16::from_le_bytes(zip[at + 26..at + 28].try_into().unwrap()) as usize;
|
||||
let data = at + 30 + len;
|
||||
if &zip[at + 30..data] == b"word/document.xml" {
|
||||
std::io::Read::read_to_string(&mut flate2::read::DeflateDecoder::new(&zip[data..data + size]), &mut xml).unwrap();
|
||||
break;
|
||||
}
|
||||
at = data + size;
|
||||
}
|
||||
assert!(xml.contains("rotation:315.000"), "diagonal text survives extraction: {xml}");
|
||||
assert!(xml.contains("z-index:-2"), "the large watermark stays behind the invoice");
|
||||
assert!(!xml.contains("<wp:inline>") && !xml.contains("<w:tbl>"));
|
||||
assert!(!xml.contains("w:val=\"single\""));
|
||||
assert_eq!(xml.matches(">DRAFT</w:t>").count(), 1);
|
||||
assert_eq!(xml.matches(">Total due: 150.00</w:t>").count(), 1);
|
||||
assert_eq!(xml.matches("<w:sectPr>").count(), 1);
|
||||
assert!(!xml.contains("w:type=\"page\""));
|
||||
assert!(xml.contains("margin-left:20.000pt"), "invoice fields retain their left edge");
|
||||
// Inspect the actual package emitted by the tool, read back as Word reads it.
|
||||
use craft_wordmodel::InlineObject;
|
||||
use craft_wordmodel::para::Wrap;
|
||||
let word = craft_docx::read(&std::fs::read(dir.join("invoice.docx")).unwrap()).unwrap();
|
||||
assert!(word.body.iter().all(|b| matches!(&**b, craft_wordmodel::Block::Para(_))), "no table");
|
||||
let objects: Vec<&InlineObject> =
|
||||
word.body.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None }).flat_map(|p| &p.objects).collect();
|
||||
let text_of = |o: &InlineObject| match o {
|
||||
InlineObject::Shape { story: Some(id), .. } => word.parts.get(id).map(|p| {
|
||||
p.blocks.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }).collect::<String>()
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let boxes: Vec<(String, &craft_wordmodel::para::Float)> = objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Shape { float, .. } => text_of(o).map(|t| (t, float)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let draft: Vec<_> = boxes.iter().filter(|(t, _)| t == "DRAFT").collect();
|
||||
assert_eq!(draft.len(), 1, "{boxes:?}");
|
||||
assert!((draft[0].1.rot - 315.0).abs() < 0.01, "diagonal text survives extraction: {}", draft[0].1.rot);
|
||||
assert_eq!(draft[0].1.wrap, Wrap::BehindText, "the large watermark stays behind the invoice");
|
||||
assert!(boxes.iter().filter(|(t, _)| t != "DRAFT").all(|(_, f)| f.z > draft[0].1.z));
|
||||
assert!(!objects.iter().any(|o| matches!(o, InlineObject::Image { float, .. } if float.wrap == Wrap::Inline)));
|
||||
assert_eq!(boxes.iter().filter(|(t, _)| t == "Total due: 150.00").count(), 1);
|
||||
assert_eq!(word.sections().len(), 1);
|
||||
assert!(!word.body.iter().any(|b| matches!(&**b, craft_wordmodel::Block::Para(p) if p.text.contains(craft_wordmodel::para::PAGE_BREAK))));
|
||||
let description = boxes.iter().find(|(t, _)| t == "Description").expect("the Description field");
|
||||
assert_eq!(description.1.x, 20.0, "invoice fields retain their left edge");
|
||||
let rendered = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap();
|
||||
assert!(rendered.iter().any(|c| matches!(c, Content::Png { .. })));
|
||||
}
|
||||
|
||||
@@ -329,9 +329,8 @@ impl crate::Document {
|
||||
/// [`Self::export_office`], and the pages whose text it had to leave out
|
||||
/// ([`OfficeExport::truncated_pages`]).
|
||||
pub fn export_office_checked(&self, format: OfficeFormat) -> OfficeExport {
|
||||
// RTF and Markdown leave pictures out.
|
||||
let (pages, truncated_pages) =
|
||||
self.export_pages_checked(!matches!(format, OfficeFormat::Rtf | OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES);
|
||||
// Markdown leaves pictures out.
|
||||
let (pages, truncated_pages) = self.export_pages_checked(!matches!(format, OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES);
|
||||
let title = self.info.title.clone().unwrap_or_else(|| self.name.trim_end_matches(".pdf").to_string());
|
||||
// Word and HTML name the document's language (`/Lang`), so spelling is checked in it.
|
||||
let language = self.initial_view().language;
|
||||
@@ -340,7 +339,7 @@ impl crate::Document {
|
||||
OfficeFormat::Pptx => pdfcraft_export::pptx(&pages, &title),
|
||||
OfficeFormat::Html => pdfcraft_export::html_with_language(&pages, &title, language.as_deref()).into_bytes(),
|
||||
OfficeFormat::HtmlSimple => pdfcraft_export::html_simple_with_language(&pages, &title, language.as_deref()).into_bytes(),
|
||||
OfficeFormat::Rtf => pdfcraft_export::rtf(&pages).into_bytes(),
|
||||
OfficeFormat::Rtf => pdfcraft_export::rtf_with_title(&pages, &title).into_bytes(),
|
||||
OfficeFormat::Markdown => pdfcraft_export::markdown(&pages).into_bytes(),
|
||||
};
|
||||
OfficeExport { bytes, truncated_pages }
|
||||
|
||||
@@ -14,7 +14,9 @@ workspace = true
|
||||
craft-markdown.workspace = true
|
||||
craft-mime.workspace = true
|
||||
craft-opc.workspace = true
|
||||
craft-rtf.workspace = true
|
||||
craft-rtf = { workspace = true, features = ["doc"] }
|
||||
craft-wordmodel.workspace = true
|
||||
craft-docx.workspace = true
|
||||
craft-xml.workspace = true
|
||||
craft-zip.workspace = true
|
||||
|
||||
|
||||
+16
-355
@@ -1,7 +1,10 @@
|
||||
use super::as_html::language_tag;
|
||||
use super::layout::{Image, Item, Page, Table, body_size, items, reading_order};
|
||||
use craft_opc::{PackageOut, RT_BASE, RelOut, RelsOut};
|
||||
use craft_xml::{Writer, esc};
|
||||
//! Word (.docx) through craft-docx (storytold/craft-libs#793): the pages are mapped onto a
|
||||
//! `craft_wordmodel::Document` ([`super::as_word`]); pages that can't flow keep their layout as
|
||||
//! positioned text boxes and pictures.
|
||||
|
||||
use super::as_word::{Meta, word_doc};
|
||||
use super::layout::{Image, Page};
|
||||
use craft_xml::Writer;
|
||||
|
||||
pub(crate) fn core_properties_xml(title: &str) -> Vec<u8> {
|
||||
let mut w = Writer::document();
|
||||
@@ -37,112 +40,6 @@ pub(crate) fn hex(c: [f64; 3]) -> Option<String> {
|
||||
(r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}"))
|
||||
}
|
||||
|
||||
/// A formatted text run (shared by paragraphs and table cells).
|
||||
fn run_xml(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) -> String {
|
||||
let mut rpr = String::new();
|
||||
if bold {
|
||||
rpr.push_str("<w:b/>");
|
||||
}
|
||||
if italic {
|
||||
rpr.push_str("<w:i/>");
|
||||
}
|
||||
if let Some(h) = hex(color) {
|
||||
rpr.push_str(&format!("<w:color w:val=\"{h}\"/>"));
|
||||
}
|
||||
let half_points = if size.is_finite() { (size * 2.0).round().clamp(2.0, 3276.0) as i64 } else { 24 };
|
||||
rpr.push_str(&format!("<w:sz w:val=\"{half_points}\"/>"));
|
||||
format!("<w:r><w:rPr>{rpr}</w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>", esc(text))
|
||||
}
|
||||
|
||||
/// One Word table: when the page's rules draw its grid, single inside borders and single outer
|
||||
/// borders on the edges they rule; explicit absent borders otherwise (alignment alone cannot
|
||||
/// prove PDF rules), a grid sized from the detected column
|
||||
/// edges, `gridSpan` for spanning cells, empty cells for holes.
|
||||
pub(crate) fn docx_table(t: &Table) -> String {
|
||||
let mut edges = t.cols.clone();
|
||||
edges.push(t.rect[2]);
|
||||
let widths: Vec<i64> = edges.windows(2).map(|w| ((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) as i64).collect();
|
||||
let mut s = String::from("<w:tbl><w:tblPr><w:tblW w:w=\"0\" w:type=\"auto\"/><w:tblBorders>");
|
||||
let [top, left, bottom, right] = t.ruled.unwrap_or_default();
|
||||
let inside = t.ruled.is_some();
|
||||
for (edge, drawn) in [("top", top), ("left", left), ("bottom", bottom), ("right", right), ("insideH", inside), ("insideV", inside)] {
|
||||
if drawn {
|
||||
s.push_str(&format!("<w:{edge} w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\"/>"));
|
||||
} else {
|
||||
s.push_str(&format!("<w:{edge} w:val=\"nil\"/>"));
|
||||
}
|
||||
}
|
||||
s.push_str("</w:tblBorders></w:tblPr><w:tblGrid>");
|
||||
for w in &widths {
|
||||
s.push_str(&format!("<w:gridCol w:w=\"{w}\"/>"));
|
||||
}
|
||||
s.push_str("</w:tblGrid>");
|
||||
for row in &t.rows {
|
||||
s.push_str("<w:tr>");
|
||||
let mut column = 0usize;
|
||||
for c in row {
|
||||
let span = if c.span > 1 { format!("<w:gridSpan w:val=\"{}\"/>", c.span) } else { String::new() };
|
||||
let w: i64 = widths.iter().skip(column).take(c.span).sum();
|
||||
s.push_str(&format!(
|
||||
"<w:tc><w:tcPr><w:tcW w:w=\"{w}\" w:type=\"dxa\"/>{span}</w:tcPr><w:p>{}</w:p></w:tc>",
|
||||
run_xml(&c.text, c.size, c.bold, c.italic, c.color)
|
||||
));
|
||||
column = column.saturating_add(c.span);
|
||||
}
|
||||
// Pad the grid so every row covers all columns (Word rejects short rows).
|
||||
for _ in column..t.cols.len() {
|
||||
s.push_str("<w:tc><w:tcPr><w:tcW w:w=\"0\" w:type=\"auto\"/></w:tcPr><w:p/></w:tc>");
|
||||
}
|
||||
s.push_str("</w:tr>");
|
||||
}
|
||||
s.push_str("</w:tbl>");
|
||||
s
|
||||
}
|
||||
|
||||
/// Pages with rotated text, or text that actually overlaps an image or an oversized
|
||||
/// (watermark-like) text block, cannot be put in paragraph flow without changing their layout.
|
||||
/// Keep those pages as editable, absolutely positioned text boxes. Every other page, including
|
||||
/// one with a logo or a big title that sits clear of the text, flows as paragraphs and tables.
|
||||
fn positioned(page: &Page) -> bool {
|
||||
if page.blocks.iter().any(|b| b.rotation.abs() > 0.1) {
|
||||
return true;
|
||||
}
|
||||
let body = body_size(std::slice::from_ref(page)).max(1.0);
|
||||
let overlays = page
|
||||
.images
|
||||
.iter()
|
||||
.map(|im| (im.rect, None))
|
||||
.chain(page.blocks.iter().enumerate().filter(|(_, b)| b.size >= 2.0 * body).map(|(i, b)| (b.rect, Some(i))));
|
||||
// Bound the pairwise test on hostile pages (many overlays times many blocks): past the
|
||||
// budget, keep the default flowing layout.
|
||||
let mut budget: usize = 1_000_000;
|
||||
for (r, own) in overlays {
|
||||
for (i, b) in page.blocks.iter().enumerate() {
|
||||
if budget == 0 {
|
||||
return false;
|
||||
}
|
||||
budget -= 1;
|
||||
if Some(i) != own && overlaps(r, b.rect) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether two [x0, y0, x1, y1] boxes share more than a hairline (0.5 pt each way); boxes that
|
||||
/// only touch, or hostile non-finite coordinates, do not count.
|
||||
fn overlaps(a: [f64; 4], b: [f64; 4]) -> bool {
|
||||
let w = a[2].min(b[2]) - a[0].max(b[0]);
|
||||
let h = a[3].min(b[3]) - a[1].max(b[1]);
|
||||
w.is_finite() && h.is_finite() && w > 0.5 && h > 0.5
|
||||
}
|
||||
|
||||
/// Bound every value written into a shape's style, including hostile PDF coordinates.
|
||||
fn layout_number(n: f64) -> f64 {
|
||||
if n.is_finite() { n.clamp(-1584.0, 1584.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Most images a Word export embeds, and most image bytes (the zip writer has 32-bit sizes and
|
||||
/// a 16-bit entry count; a hostile PDF must not be able to overflow them).
|
||||
pub(crate) const MAX_MEDIA: usize = 1000;
|
||||
@@ -156,135 +53,12 @@ pub(crate) fn room_for(media: &[(String, &Image)], im: &Image) -> bool {
|
||||
&& media.iter().map(|(_, m)| m.bytes.len()).fold(im.bytes.len(), usize::saturating_add) <= MAX_MEDIA_BYTES
|
||||
}
|
||||
|
||||
/// Points as EMU (12700 per point); non-finite values are 0.
|
||||
fn emu(pt: f64) -> i64 {
|
||||
if pt.is_finite() { (pt * 12700.0).round() as i64 } else { 0 }
|
||||
}
|
||||
/// The body text's font. A reader without Arial draws it in a sans-serif: the font table says
|
||||
/// it is one (Word and LibreOffice substitute their own sans, LibreOffice Liberation Sans).
|
||||
const FONT: &str = "Arial";
|
||||
|
||||
/// The `a:graphic` of one picture (DrawingML), rotated by `rotation` degrees when given.
|
||||
fn picture_xml(n: usize, name: &str, (cx, cy): (i64, i64), rotation: Option<f64>) -> String {
|
||||
let rot = rotation.map_or(String::new(), |r| format!(" rot=\"{}\"", (r * 60000.0).round() as i64));
|
||||
format!(
|
||||
"<wp:docPr id=\"{n}\" name=\"Picture {n}\"/><wp:cNvGraphicFramePr/>\
|
||||
<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">\
|
||||
<pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:nvPicPr><pic:cNvPr id=\"{n}\" name=\"{name}\"/><pic:cNvPicPr/></pic:nvPicPr>\
|
||||
<pic:blipFill><a:blip r:embed=\"rIdImg{n}\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>\
|
||||
<pic:spPr><a:xfrm{rot}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>\
|
||||
</a:graphicData></a:graphic>"
|
||||
)
|
||||
}
|
||||
|
||||
fn positioned_page<'a>(page: &'a Page, media: &mut Vec<(String, &'a Image)>, shape_id: &mut usize) -> String {
|
||||
// One 1 pt paragraph anchors the whole page. Shapes never reserve body space, so even a
|
||||
// page-sized watermark cannot push the invoice footer onto another page.
|
||||
let mut s = String::from("<w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\" w:line=\"20\" w:lineRule=\"exact\"/></w:pPr>");
|
||||
let body = body_size(std::slice::from_ref(page)).max(1.0);
|
||||
// Rotated pages are positioned shapes, so paragraph flow never orders them. Emit the
|
||||
// text boxes in reading order; the file's block order is not the reading order.
|
||||
let blocks = reading_order(page, page.blocks.iter().map(|b| (b.rect, b.size, b)).collect());
|
||||
for b in blocks {
|
||||
*shape_id = shape_id.saturating_add(1);
|
||||
let rotation = layout_number(-b.rotation).rem_euclid(360.0);
|
||||
let (sin, cos) = rotation.to_radians().sin_cos();
|
||||
let (bw, bh) = (layout_number(b.rect[2] - b.rect[0]).max(1.0), layout_number(b.rect[3] - b.rect[1]).max(1.0));
|
||||
let h = if b.rotation.abs() > 0.1 { layout_number(b.size).max(1.0) } else { bh };
|
||||
// Recover the unrotated width from the axis-aligned box. Use the larger axis so
|
||||
// quarter turns and 45-degree watermarks do not divide by (nearly) zero.
|
||||
let w = if b.rotation.abs() <= 0.1 {
|
||||
bw
|
||||
} else if cos.abs() >= sin.abs() {
|
||||
(bw - h * sin.abs()) / cos.abs()
|
||||
} else {
|
||||
(bh - h * cos.abs()) / sin.abs()
|
||||
};
|
||||
let w = layout_number(w).max(1.0);
|
||||
let (x, y) = (layout_number(b.rect[0] + (bw - w) / 2.0), layout_number(page.height - b.rect[3] + (bh - h) / 2.0));
|
||||
let z = if b.size >= 2.0 * body { -2 } else { 1 };
|
||||
let style = format!(
|
||||
"position:absolute;margin-left:{x:.3}pt;margin-top:{y:.3}pt;width:{w:.3}pt;height:{h:.3}pt;rotation:{rotation:.3};z-index:{z};mso-position-horizontal-relative:page;mso-position-vertical-relative:page"
|
||||
);
|
||||
s.push_str(&format!(
|
||||
"<w:r><w:pict><v:rect id=\"Text{}\" style=\"{style}\" filled=\"f\" stroked=\"f\"><v:textbox inset=\"0,0,0,0\" style=\"mso-fit-shape-to-text:t\"><w:txbxContent><w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\"/></w:pPr>{}</w:p></w:txbxContent></v:textbox><w10:wrap type=\"none\"/></v:rect></w:pict></w:r>",
|
||||
shape_id, run_xml(&b.text, b.size, b.bold, b.italic, b.color)
|
||||
));
|
||||
}
|
||||
for im in &page.images {
|
||||
if !room_for(media, im) {
|
||||
continue;
|
||||
}
|
||||
*shape_id = shape_id.saturating_add(1);
|
||||
let n = media.len().saturating_add(1);
|
||||
let (w, h) = (layout_number(im.size[0]).max(1.0), layout_number(im.size[1]).max(1.0));
|
||||
let (x, y) = (layout_number((im.rect[0] + im.rect[2] - w) / 2.0), layout_number(page.height - (im.rect[1] + im.rect[3] + h) / 2.0));
|
||||
let rotation = layout_number(-im.rotation).rem_euclid(360.0);
|
||||
let name = format!("image{n}.{}", im.ext);
|
||||
let pic = picture_xml(n, &name, (emu(w), emu(h)), Some(rotation));
|
||||
// A DrawingML anchor, the way Word itself stores a picture placed behind text: a VML
|
||||
// rectangle with an image does not show the picture.
|
||||
s.push_str(&format!(
|
||||
"<w:r><w:drawing><wp:anchor distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\" simplePos=\"0\" relativeHeight=\"{}\" behindDoc=\"1\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">\
|
||||
<wp:simplePos x=\"0\" y=\"0\"/><wp:positionH relativeFrom=\"page\"><wp:posOffset>{}</wp:posOffset></wp:positionH><wp:positionV relativeFrom=\"page\"><wp:posOffset>{}</wp:posOffset></wp:positionV>\
|
||||
<wp:extent cx=\"{}\" cy=\"{}\"/><wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/><wp:wrapNone/>",
|
||||
n.saturating_add(1),
|
||||
emu(x),
|
||||
emu(y),
|
||||
emu(w),
|
||||
emu(h),
|
||||
));
|
||||
s.push_str(&pic);
|
||||
s.push_str("</wp:anchor></w:drawing></w:r>");
|
||||
media.push((name, im));
|
||||
}
|
||||
s.push_str("</w:p>");
|
||||
s
|
||||
}
|
||||
|
||||
fn word_page_size(page: &Page) -> (i64, i64) {
|
||||
let twips = |pt: f64| if pt.is_finite() { (pt * 20.0).round().clamp(144.0, 31680.0) as i64 } else { 12240 };
|
||||
(twips(page.width), twips(page.height))
|
||||
}
|
||||
|
||||
fn section(page: &Page) -> String {
|
||||
let (pw, ph) = word_page_size(page);
|
||||
let (mx, my) = ((pw / 8).min(1440), (ph / 8).min(1440));
|
||||
format!(
|
||||
"<w:sectPr><w:type w:val=\"nextPage\"/><w:pgSz w:w=\"{pw}\" w:h=\"{ph}\"/><w:pgMar w:top=\"{my}\" w:right=\"{mx}\" w:bottom=\"{my}\" w:left=\"{mx}\" w:header=\"{}\" w:footer=\"{}\" w:gutter=\"0\"/></w:sectPr>",
|
||||
my / 2,
|
||||
my / 2
|
||||
)
|
||||
}
|
||||
|
||||
/// The page colour of a Word document: Word has one background for the whole document, so it
|
||||
/// is written only when every page has the same, non-white background (#2992).
|
||||
fn word_background(pages: &[Page]) -> Option<String> {
|
||||
let first = rgb8(pages.first()?.background?);
|
||||
let same = pages.iter().all(|p| p.background.map(rgb8) == Some(first));
|
||||
(same && first != [255, 255, 255]).then(|| format!("{:02X}{:02X}{:02X}", first[0], first[1], first[2]))
|
||||
}
|
||||
|
||||
/// The `w:lang` that makes `tag` the language of a Word document's text. Word keeps one language
|
||||
/// per script: Chinese, Japanese and Korean are its East Asian text, Arabic, Hebrew, Persian and
|
||||
/// Urdu its right-to-left text, and any other language its Latin, Greek and Cyrillic text. A
|
||||
/// script the tag names (`pa-Arab`, `zh-Latn`) decides over its language.
|
||||
fn word_lang(tag: &str) -> String {
|
||||
let mut subtags = tag.split('-');
|
||||
let primary = subtags.next().unwrap_or_default().to_ascii_lowercase();
|
||||
// The script comes straight after the language and any three-letter extended languages; a
|
||||
// singleton before it starts an extension or private use, which names no script.
|
||||
let script = subtags
|
||||
.find(|s| s.len() != 3 || !s.bytes().all(|b| b.is_ascii_alphabetic()))
|
||||
.filter(|s| s.len() == 4 && s.bytes().all(|b| b.is_ascii_alphabetic()))
|
||||
.map(str::to_ascii_lowercase);
|
||||
let attribute = match (script.as_deref(), primary.as_str()) {
|
||||
(Some("arab" | "hebr" | "syrc" | "thaa"), _) => "w:bidi",
|
||||
(Some("hans" | "hant" | "hani" | "jpan" | "kore" | "hang" | "hira" | "kana"), _) => "w:eastAsia",
|
||||
(Some("latn" | "cyrl" | "grek"), _) => "w:val",
|
||||
(_, "zh" | "ja" | "ko") => "w:eastAsia",
|
||||
(_, "ar" | "he" | "fa" | "ur") => "w:bidi",
|
||||
_ => "w:val",
|
||||
};
|
||||
format!("<w:lang {attribute}=\"{}\"/>", esc(tag))
|
||||
}
|
||||
/// The application `docProps/app.xml` names.
|
||||
const APPLICATION: &str = "PdfCraft";
|
||||
|
||||
/// A Word document (.docx, Office Open XML). Ordinary pages flow as paragraphs and tables;
|
||||
/// pages with rotated text, or text that overlaps artwork, use floating shapes to retain their layout.
|
||||
@@ -296,121 +70,8 @@ pub fn docx(pages: &[Page], title: &str) -> Vec<u8> {
|
||||
/// it): the default language of its text, so Word checks the spelling in that language rather
|
||||
/// than in its own. A language that is not a well formed tag is left out.
|
||||
pub fn docx_with_language(pages: &[Page], title: &str, language: Option<&str>) -> Vec<u8> {
|
||||
let mut body = String::new();
|
||||
let mut media: Vec<(String, &Image)> = Vec::new();
|
||||
// Word needs a paragraph between adjacent tables and after the last one in the body.
|
||||
let mut after_table = false;
|
||||
let mut shape_id = 0usize;
|
||||
for (page_index, page) in pages.iter().enumerate() {
|
||||
let (pw, _) = word_page_size(page);
|
||||
let text_w = (pw - 2 * (pw / 8).min(1440)) as f64 / 20.0;
|
||||
if positioned(page) {
|
||||
body.push_str(&positioned_page(page, &mut media, &mut shape_id));
|
||||
after_table = false;
|
||||
} else {
|
||||
for it in items(std::slice::from_ref(page)) {
|
||||
match &it {
|
||||
Item::Para(runs, lvl) => {
|
||||
let style = match lvl {
|
||||
1 => "<w:pPr><w:pStyle w:val=\"Heading1\"/></w:pPr>",
|
||||
2 => "<w:pPr><w:pStyle w:val=\"Heading2\"/></w:pPr>",
|
||||
_ => "",
|
||||
};
|
||||
body.push_str("<w:p>");
|
||||
body.push_str(style);
|
||||
for r in runs {
|
||||
body.push_str(&run_xml(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color));
|
||||
}
|
||||
body.push_str("</w:p>");
|
||||
}
|
||||
Item::Table(t) => {
|
||||
if after_table {
|
||||
body.push_str("<w:p/>");
|
||||
}
|
||||
body.push_str(&docx_table(t));
|
||||
}
|
||||
Item::Img(im) => {
|
||||
if room_for(&media, im) {
|
||||
let n = media.len() + 1;
|
||||
let name = format!("image{n}.{}", im.ext);
|
||||
// Size on the page, at most the text width.
|
||||
let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0));
|
||||
let k = (text_w / w).min(1.0);
|
||||
let (cx, cy) = (emu(w * k), emu(h * k));
|
||||
body.push_str(&format!("<w:p><w:r><w:drawing><wp:inline><wp:extent cx=\"{cx}\" cy=\"{cy}\"/>"));
|
||||
body.push_str(&picture_xml(n, &name, (cx, cy), None));
|
||||
body.push_str("</wp:inline></w:drawing></w:r></w:p>");
|
||||
media.push((name, im));
|
||||
}
|
||||
}
|
||||
Item::PageBreak => body.push_str("<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>"),
|
||||
}
|
||||
after_table = matches!(it, Item::Table(_));
|
||||
}
|
||||
}
|
||||
// Section breaks carry this source page's size and create exactly one next page.
|
||||
// The last section must be a direct child of the body (OOXML 17.6.17).
|
||||
if page_index + 1 < pages.len() {
|
||||
body.push_str(&format!(
|
||||
"<w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\" w:line=\"20\" w:lineRule=\"exact\"/>{}</w:pPr></w:p>",
|
||||
section(page)
|
||||
));
|
||||
} else {
|
||||
if after_table || page.blocks.is_empty() && page.images.is_empty() {
|
||||
body.push_str("<w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"20\" w:lineRule=\"exact\"/></w:pPr></w:p>");
|
||||
}
|
||||
body.push_str(§ion(page));
|
||||
}
|
||||
after_table = false;
|
||||
}
|
||||
// Word shows a document background only when its settings say so (`settings.xml` below).
|
||||
let page_colour = word_background(pages);
|
||||
let background = page_colour.as_deref().map(|c| format!("<w:background w:color=\"{c}\"/>")).unwrap_or_default();
|
||||
let doc = format!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
|
||||
<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" \
|
||||
xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\">{background}<w:body>{body}\
|
||||
</w:body></w:document>"
|
||||
);
|
||||
let mut pkg = PackageOut::default();
|
||||
let mut root_rels = RelsOut::default();
|
||||
root_rels.add("officeDocument", "word/document.xml", false);
|
||||
root_rels.add("metadata/core-properties", "docProps/core.xml", false);
|
||||
pkg.rels("", &root_rels);
|
||||
|
||||
let mut doc_rels = RelsOut::default();
|
||||
doc_rels.items.push(RelOut { id: "rIdStyles".into(), ty: format!("{RT_BASE}styles"), target: "styles.xml".into(), external: false });
|
||||
for (i, (name, im)) in media.iter().enumerate() {
|
||||
doc_rels.items.push(RelOut {
|
||||
id: format!("rIdImg{}", i + 1),
|
||||
ty: format!("{RT_BASE}image"),
|
||||
target: format!("media/{name}"),
|
||||
external: false,
|
||||
});
|
||||
pkg.binary(&format!("word/media/{name}"), image_mime(im.ext), im.bytes.to_vec());
|
||||
}
|
||||
if page_colour.is_some() {
|
||||
doc_rels.items.push(RelOut { id: "rIdSettings".into(), ty: format!("{RT_BASE}settings"), target: "settings.xml".into(), external: false });
|
||||
}
|
||||
pkg.rels("word/document.xml", &doc_rels);
|
||||
let defaults = language_tag(language)
|
||||
.map(|tag| format!("<w:docDefaults><w:rPrDefault><w:rPr>{}</w:rPr></w:rPrDefault></w:docDefaults>", word_lang(tag)))
|
||||
.unwrap_or_default();
|
||||
let styles = format!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<w:styles xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">{defaults}\
|
||||
<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/><w:pPr><w:spacing w:after=\"120\"/></w:pPr></w:style>\
|
||||
<w:style w:type=\"paragraph\" w:styleId=\"Heading1\"><w:name w:val=\"heading 1\"/><w:basedOn w:val=\"Normal\"/><w:next w:val=\"Normal\"/><w:pPr><w:keepNext/><w:spacing w:before=\"240\"/><w:outlineLvl w:val=\"0\"/></w:pPr><w:rPr><w:b/></w:rPr></w:style>\
|
||||
<w:style w:type=\"paragraph\" w:styleId=\"Heading2\"><w:name w:val=\"heading 2\"/><w:basedOn w:val=\"Normal\"/><w:next w:val=\"Normal\"/><w:pPr><w:keepNext/><w:spacing w:before=\"200\"/><w:outlineLvl w:val=\"1\"/></w:pPr><w:rPr><w:b/></w:rPr></w:style>\
|
||||
</w:styles>"
|
||||
);
|
||||
pkg.xml_part("docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml", core_properties_xml(title));
|
||||
pkg.xml_part("word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", doc.into_bytes());
|
||||
pkg.xml_part("word/styles.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", styles.into_bytes());
|
||||
if page_colour.is_some() {
|
||||
let mut settings = Writer::document();
|
||||
settings.open("w:settings", &[("xmlns:w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]);
|
||||
settings.empty("w:displayBackgroundShape", &[]);
|
||||
pkg.xml_part("word/settings.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", settings.into_bytes());
|
||||
}
|
||||
pkg.finish().unwrap_or_default()
|
||||
craft_docx::set_application_name(APPLICATION);
|
||||
// Writing a document built here fails only on a hostile size the mapping already bounds; an
|
||||
// empty result is what the export returned for a package it couldn't finish.
|
||||
craft_docx::write(&word_doc(pages, &Meta { title, language, font: FONT })).unwrap_or_default()
|
||||
}
|
||||
+17
-84
@@ -1,90 +1,23 @@
|
||||
//! Rich Text Format through craft-rtf's writer: this module maps the pages onto its small model
|
||||
//! (storytold/craft-libs#793).
|
||||
//! Rich Text Format through craft-rtf's full writer (storytold/craft-libs#793): the pages are
|
||||
//! mapped onto a `craft_wordmodel::Document` ([`super::as_word`]), every page flowing.
|
||||
|
||||
use super::as_docx::rgb8;
|
||||
use super::as_html::allowed;
|
||||
use super::layout::{Item, Page, Table, items};
|
||||
use craft_rtf::{Block, Cell, CharFmt, Document, PAGE_BREAK, Para, Run};
|
||||
use super::as_word::{Meta, flow_doc};
|
||||
use super::layout::Page;
|
||||
|
||||
/// The text as RTF may hold it: the characters Word refuses are left out.
|
||||
fn clean(s: &str) -> String {
|
||||
s.chars().filter(|c| allowed(*c)).collect()
|
||||
}
|
||||
/// The body text's font, as PdfCraft's RTF has always named it (a reader without Helvetica draws
|
||||
/// it in its sans-serif, which the font table's `\fswiss` asks for).
|
||||
const FONT: &str = "Helvetica";
|
||||
|
||||
/// A run's formatting: its size in half points, bold, italic and colour (none for black, which
|
||||
/// is the default).
|
||||
fn char_fmt(size: f64, bold: bool, italic: bool, color: [f64; 3]) -> CharFmt {
|
||||
let color = Some(rgb8(color)).filter(|c| *c != [0, 0, 0]);
|
||||
// A size that is not finite or below zero becomes 0, as the cast saturates.
|
||||
CharFmt { bold, italic, half_points: Some((size * 2.0).round() as u32), color, ..CharFmt::default() }
|
||||
}
|
||||
/// The application the RTF names as its writer (`{\*\generator}`).
|
||||
pub(crate) const GENERATOR: &str = "PdfCraft";
|
||||
|
||||
/// A table's rows. Each cell ends at the right edge of the last grid column it spans, in twips.
|
||||
fn table(t: &Table) -> craft_rtf::Table {
|
||||
let mut edges = t.cols.clone();
|
||||
edges.push(t.rect[2]);
|
||||
let cellx: Vec<i32> = edges.iter().skip(1).map(|e| (e * 20.0).round() as i32).collect();
|
||||
let rows = t
|
||||
.rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let mut column = 0;
|
||||
row.iter()
|
||||
.map(|c| {
|
||||
column += c.span.max(1);
|
||||
let right = cellx.get(column.min(cellx.len()).saturating_sub(1)).copied().unwrap_or(0);
|
||||
let run = Run { text: clean(&c.text), fmt: char_fmt(c.size, c.bold, c.italic, c.color) };
|
||||
Cell { right, paras: vec![Para { runs: vec![run], ..Para::default() }] }
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
craft_rtf::Table { rows }
|
||||
}
|
||||
|
||||
/// Keep a break outside tables, including when no text follows it on its page.
|
||||
fn standalone_page_break(blocks: &mut Vec<Block>) {
|
||||
let run = Run { text: PAGE_BREAK.to_string(), fmt: CharFmt::default() };
|
||||
blocks.push(Block::Para(Para { runs: vec![run], ..Para::default() }));
|
||||
}
|
||||
|
||||
/// Rich Text Format: paragraphs with their sizes, bold, italic and colours, real table rows, page
|
||||
/// breaks between pages (images are left out).
|
||||
/// Rich Text Format: paragraphs with their sizes, bold, italic and colours, headings, tables,
|
||||
/// pictures, and each page in a section of its own size.
|
||||
pub fn rtf(pages: &[Page]) -> String {
|
||||
let mut blocks = Vec::new();
|
||||
// A page break waits for what follows it: RTF's `\page` is a character in a paragraph, so it
|
||||
// starts the next one, or stands alone before a table.
|
||||
let mut page_break = false;
|
||||
for it in items(pages) {
|
||||
match it {
|
||||
Item::Para(runs, _) => {
|
||||
let mut runs: Vec<Run> = runs
|
||||
.iter()
|
||||
.map(|r| Run { text: clean(&r.text), fmt: char_fmt(r.block.size, r.block.bold, r.block.italic, r.block.color) })
|
||||
.collect();
|
||||
let Some(first) = runs.first_mut() else { continue };
|
||||
if std::mem::take(&mut page_break) {
|
||||
first.text.insert(0, PAGE_BREAK);
|
||||
}
|
||||
blocks.push(Block::Para(Para { runs, ..Para::default() }));
|
||||
}
|
||||
Item::Table(t) => {
|
||||
if std::mem::take(&mut page_break) {
|
||||
standalone_page_break(&mut blocks);
|
||||
}
|
||||
blocks.push(Block::Table(table(&t)));
|
||||
}
|
||||
Item::Img(_) => {}
|
||||
Item::PageBreak => {
|
||||
if page_break {
|
||||
standalone_page_break(&mut blocks);
|
||||
}
|
||||
page_break = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if page_break {
|
||||
standalone_page_break(&mut blocks);
|
||||
}
|
||||
craft_rtf::write(&Document { blocks, pictures_left_out: 0 }, "Helvetica")
|
||||
rtf_with_title(pages, "")
|
||||
}
|
||||
|
||||
/// [`rtf`] with the document's title (`\info\title`).
|
||||
pub fn rtf_with_title(pages: &[Page], title: &str) -> String {
|
||||
craft_rtf::doc::export_with_generator(&flow_doc(pages, &Meta { title, language: None, font: FONT }), GENERATOR)
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
//! The pages as a `craft_wordmodel::Document`, the model craft-libs' word-processing writers take
|
||||
//! (storytold/craft-libs#793): paragraphs with their runs and heading levels, tables, pictures,
|
||||
//! and a section per page with that page's size. RTF writes it with craft-rtf's full writer, every
|
||||
//! page flowing ([`flow_doc`]); Word writes it with craft-docx, pages that can't flow kept as
|
||||
//! positioned text boxes and pictures ([`word_doc`]).
|
||||
|
||||
use super::as_docx::{rgb8, room_for};
|
||||
use super::as_html::{allowed, language_tag};
|
||||
use super::layout::{Image, Item, Page, Table, body_size, items, reading_order};
|
||||
use craft_wordmodel::para::{Anchor, Float, ShapeKind, Wrap};
|
||||
use craft_wordmodel::props::{Border, BorderStyle, Borders, CellProps, LineSpacing, TableProps};
|
||||
use craft_wordmodel::{Block, CharProps, Document, InlineObject, ParaProps, Paragraph, PartKind, Rgb, SectionProps, Style, StyleSheet, TextColor};
|
||||
|
||||
/// A run's formatting: its size, bold, italic and colour (none for black, the default).
|
||||
fn chr(size: f64, bold: bool, italic: bool, color: [f64; 3]) -> CharProps {
|
||||
let [r, g, b] = rgb8(color);
|
||||
// Half points, as Word and RTF store sizes; one that is not finite gets the 12 pt default.
|
||||
let half_points = if size.is_finite() { (size * 2.0).round().clamp(2.0, 3276.0) } else { 24.0 };
|
||||
CharProps {
|
||||
size: Some(half_points as f32 / 2.0),
|
||||
bold: bold.then_some(true),
|
||||
italic: italic.then_some(true),
|
||||
color: (r | g | b != 0).then_some(TextColor::Rgb(Rgb(r, g, b))),
|
||||
..CharProps::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends `text` to `p` as a run (`Paragraph::push_text` drops U+FFFC, the model's object mark,
|
||||
/// which in the PDF's text is a character, not an object), keeping only the characters Word and
|
||||
/// RTF readers accept.
|
||||
fn push_text(p: &mut Paragraph, text: &str, props: CharProps) {
|
||||
// A hard line ending in the text (LF, CR or CRLF) is a line break, the model's `\n`, which the
|
||||
// writers keep inside its paragraph or cell (storytold/pdfcraft#4723).
|
||||
let text = text.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let text: String = text.chars().filter(|c| allowed(*c)).collect();
|
||||
p.push_text(&text, &props);
|
||||
}
|
||||
|
||||
/// A table: its grid from the column edges, ruled where the PDF draws rules, one paragraph per
|
||||
/// cell.
|
||||
pub(crate) fn table(t: &Table) -> craft_wordmodel::Table {
|
||||
let mut edges = t.cols.clone();
|
||||
edges.push(t.rect[2]);
|
||||
// Whole twips, at least 3 pt wide (Word's narrowest column), as `as_docx` writes them.
|
||||
let widths: Vec<f32> = edges.windows(2).map(|w| (((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) / 20.0) as f32).collect();
|
||||
let [top, left, bottom, right] = t.ruled.unwrap_or_default();
|
||||
let inside = t.ruled.is_some();
|
||||
let rule = |drawn: bool| Some(if drawn { Border { style: BorderStyle::Single, width: 0.5, color: None, space: 0.0 } } else { Border::default() });
|
||||
let props = TableProps {
|
||||
borders: Some(Borders {
|
||||
top: rule(top),
|
||||
left: rule(left),
|
||||
bottom: rule(bottom),
|
||||
right: rule(right),
|
||||
between: rule(inside),
|
||||
inside_v: rule(inside),
|
||||
}),
|
||||
..TableProps::default()
|
||||
};
|
||||
let rows = t
|
||||
.rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let mut cells = Vec::new();
|
||||
let mut column = 0usize;
|
||||
for c in row {
|
||||
let span = c.span.max(1);
|
||||
let w: f32 = widths.iter().skip(column).take(span).sum();
|
||||
let mut p = Paragraph::new();
|
||||
push_text(&mut p, &c.text, chr(c.size, c.bold, c.italic, c.color));
|
||||
cells.push(craft_wordmodel::Cell {
|
||||
props: CellProps { width: Some(w), span: span as u32, ..CellProps::default() },
|
||||
blocks: vec![craft_wordmodel::para_block(p)],
|
||||
..Default::default()
|
||||
});
|
||||
column = column.saturating_add(span);
|
||||
}
|
||||
// A short row is padded to the grid, as Word expects every row to fill it.
|
||||
for w in widths.iter().skip(column) {
|
||||
cells.push(craft_wordmodel::Cell {
|
||||
props: CellProps { width: Some(*w), ..CellProps::default() },
|
||||
blocks: vec![craft_wordmodel::para_block(Paragraph::new())],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
craft_wordmodel::Row { cells, ..Default::default() }
|
||||
})
|
||||
.collect();
|
||||
craft_wordmodel::Table { props, grid: widths, rows, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A page's section: its size, with margins of an eighth of each side, at most an inch.
|
||||
fn section(page: &Page) -> SectionProps {
|
||||
let twips = |pt: f64| if pt.is_finite() { (pt * 20.0).round().clamp(144.0, 31680.0) as i64 } else { 12240 };
|
||||
let (w, h) = (twips(page.width), twips(page.height));
|
||||
let (mx, my) = ((w / 8).min(1440), (h / 8).min(1440));
|
||||
let pt = |t: i64| t as f32 / 20.0;
|
||||
SectionProps {
|
||||
page_w: pt(w),
|
||||
page_h: pt(h),
|
||||
landscape: false,
|
||||
margin_top: pt(my),
|
||||
margin_bottom: pt(my),
|
||||
margin_left: pt(mx),
|
||||
margin_right: pt(mx),
|
||||
header: pt(my / 2),
|
||||
footer: pt(my / 2),
|
||||
..SectionProps::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The document default formatting for text in `tag`. Word keeps one language per script:
|
||||
/// Chinese, Japanese and Korean are its East Asian text, Arabic, Hebrew, Persian and Urdu its
|
||||
/// right-to-left text, and any other language its Latin, Greek and Cyrillic text. A script the
|
||||
/// tag names (`pa-Arab`, `zh-Latn`) decides over its language.
|
||||
fn language(tag: &str) -> CharProps {
|
||||
let mut subtags = tag.split('-');
|
||||
let primary = subtags.next().unwrap_or_default().to_ascii_lowercase();
|
||||
// The script comes straight after the language and any three-letter extended languages; a
|
||||
// singleton before it starts an extension or private use, which names no script.
|
||||
let script = subtags
|
||||
.find(|s| s.len() != 3 || !s.bytes().all(|b| b.is_ascii_alphabetic()))
|
||||
.filter(|s| s.len() == 4 && s.bytes().all(|b| b.is_ascii_alphabetic()))
|
||||
.map(str::to_ascii_lowercase);
|
||||
let tag = Some(tag.to_string());
|
||||
match (script.as_deref(), primary.as_str()) {
|
||||
(Some("arab" | "hebr" | "syrc" | "thaa"), _) => CharProps { lang_bidi: tag, ..CharProps::default() },
|
||||
(Some("hans" | "hant" | "hani" | "jpan" | "kore" | "hang" | "hira" | "kana"), _) => CharProps { lang_ea: tag, ..CharProps::default() },
|
||||
(Some("latn" | "cyrl" | "grek"), _) => CharProps { lang: tag, ..CharProps::default() },
|
||||
(_, "zh" | "ja" | "ko") => CharProps { lang_ea: tag, ..CharProps::default() },
|
||||
(_, "ar" | "he" | "fa" | "ur") => CharProps { lang_bidi: tag, ..CharProps::default() },
|
||||
_ => CharProps { lang: tag, ..CharProps::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// The styles: the body text in `font`, in the document's language, and two heading levels.
|
||||
fn styles(font: &str, lang: Option<&str>) -> StyleSheet {
|
||||
let mut s = StyleSheet { styles: Vec::new(), ..StyleSheet::default() };
|
||||
s.default_chr = CharProps { font: Some(font.to_string()), ..language_tag(lang).map(language).unwrap_or_default() };
|
||||
// As `as_docx` set them: lines at 1.16 and 6 pt after each paragraph.
|
||||
s.default_para = ParaProps { line_spacing: Some(LineSpacing::Multiple(1.16)), ..ParaProps::default() };
|
||||
s.default_para_present = true;
|
||||
let normal = ParaProps { space_after: Some(6.0), ..ParaProps::default() };
|
||||
s.styles.push(Style { id: "Normal".into(), name: "Normal".into(), default: true, builtin: true, para: normal, ..Style::default() });
|
||||
for (lvl, before) in [(1u8, 12.0f32), (2, 10.0)] {
|
||||
s.styles.push(Style {
|
||||
id: format!("Heading{lvl}"),
|
||||
name: format!("heading {lvl}"),
|
||||
based_on: Some("Normal".into()),
|
||||
next: Some("Normal".into()),
|
||||
para: ParaProps { keep_next: Some(true), space_before: Some(before), outline_level: Some(lvl - 1), ..ParaProps::default() },
|
||||
chr: CharProps { bold: Some(true), ..CharProps::default() },
|
||||
builtin: true,
|
||||
..Style::default()
|
||||
});
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// What the document holds besides its pages.
|
||||
pub(crate) struct Meta<'a> {
|
||||
pub title: &'a str,
|
||||
/// The PDF's `/Lang`.
|
||||
pub language: Option<&'a str>,
|
||||
/// The body text's font.
|
||||
pub font: &'a str,
|
||||
}
|
||||
|
||||
/// The document being built: the model, its body, and the pictures it has embedded so far (for
|
||||
/// the export's limits on their count and size, [`room_for`]).
|
||||
struct Builder<'a> {
|
||||
doc: Document,
|
||||
body: Vec<Block>,
|
||||
media: Vec<(String, &'a Image)>,
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a> {
|
||||
fn new(pages: &[Page], meta: &Meta) -> Self {
|
||||
let mut doc = Document::new();
|
||||
doc.styles = std::sync::Arc::new(styles(meta.font, meta.language));
|
||||
doc.core.title = meta.title.to_string();
|
||||
// A background every page shares is the document's page colour (#2992): Word has one for
|
||||
// the whole document.
|
||||
let shared = pages.first().and_then(|p| p.background).map(rgb8);
|
||||
if let Some(c) = shared.filter(|c| *c != [255; 3] && pages.iter().all(|p| p.background.map(rgb8) == Some(*c))) {
|
||||
doc.settings.page_color = Some(Rgb(c[0], c[1], c[2]));
|
||||
}
|
||||
Builder { doc, body: Vec::new(), media: Vec::new() }
|
||||
}
|
||||
|
||||
/// The media key for `im`, or `None` past the limits.
|
||||
fn add_media(&mut self, im: &'a Image) -> Option<String> {
|
||||
if !room_for(&self.media, im) {
|
||||
return None;
|
||||
}
|
||||
let key = self.doc.add_media(im.bytes.to_vec(), im.ext);
|
||||
self.media.push((key.clone(), im));
|
||||
Some(key)
|
||||
}
|
||||
|
||||
/// One flowing item: a paragraph, a table, or a picture scaled to fit between the margins of
|
||||
/// `sec`.
|
||||
fn flow(&mut self, it: Item<'a>, sec: &SectionProps) {
|
||||
match it {
|
||||
Item::Para(runs, lvl) => {
|
||||
let mut p = Paragraph::new();
|
||||
if matches!(lvl, 1 | 2) {
|
||||
p.props.style = Some(format!("Heading{lvl}"));
|
||||
}
|
||||
for r in &runs {
|
||||
push_text(&mut p, &r.text, chr(r.block.size, r.block.bold, r.block.italic, r.block.color));
|
||||
}
|
||||
self.body.push(Block::Para(p));
|
||||
}
|
||||
Item::Table(t) => {
|
||||
// Tables that touch become one table: a paragraph keeps them apart.
|
||||
if matches!(self.body.last(), Some(Block::Table(_))) {
|
||||
self.body.push(Block::Para(Paragraph::new()));
|
||||
}
|
||||
self.body.push(Block::Table(table(&t)));
|
||||
}
|
||||
Item::Img(im) => {
|
||||
let Some(media) = self.add_media(im) else { return };
|
||||
let text_w = f64::from((sec.page_w - sec.margin_left - sec.margin_right).max(1.0));
|
||||
let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0));
|
||||
let k = (text_w / w).min(1.0);
|
||||
let pic = InlineObject::Image {
|
||||
media,
|
||||
w: (w * k) as f32,
|
||||
h: (h * k) as f32,
|
||||
alt: String::new(),
|
||||
float: Float::default(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
let mut p = Paragraph::new();
|
||||
p.push_object(pic, &CharProps::default());
|
||||
self.body.push(Block::Para(p));
|
||||
}
|
||||
Item::PageBreak => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// End a page: its section ends here, and the next page's starts on a new page.
|
||||
fn end_page(&mut self, sec: SectionProps) {
|
||||
let mut p = Paragraph::new();
|
||||
p.props = exact_1pt();
|
||||
p.section = Some(Box::new(sec));
|
||||
self.body.push(Block::Para(p));
|
||||
}
|
||||
|
||||
fn finish(mut self, last: SectionProps) -> Document {
|
||||
self.doc.last_section = last;
|
||||
self.doc.body = self.body.into_iter().map(std::sync::Arc::new).collect();
|
||||
self.doc.ensure_nonempty();
|
||||
self.doc
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph that takes no room: no space around it and a 1 pt line.
|
||||
fn exact_1pt() -> ParaProps {
|
||||
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(1.0)), ..ParaProps::default() }
|
||||
}
|
||||
|
||||
/// The pages as one flowing document: each page a section of its own size (so a page always
|
||||
/// starts a new one, blank pages included), its paragraphs, tables and pictures in reading order.
|
||||
/// Headings are told from the whole document's body size.
|
||||
pub(crate) fn flow_doc(pages: &[Page], meta: &Meta) -> Document {
|
||||
let mut b = Builder::new(pages, meta);
|
||||
let mut page = 0usize;
|
||||
let mut sec = pages.first().map(section).unwrap_or_default();
|
||||
for it in items(pages) {
|
||||
if matches!(it, Item::PageBreak) {
|
||||
b.end_page(sec);
|
||||
page += 1;
|
||||
sec = pages.get(page).map(section).unwrap_or_default();
|
||||
} else {
|
||||
b.flow(it, &sec);
|
||||
}
|
||||
}
|
||||
b.finish(sec)
|
||||
}
|
||||
|
||||
/// Pages with rotated text, or text that actually overlaps an image or an oversized
|
||||
/// (watermark-like) text block, cannot be put in paragraph flow without changing their layout.
|
||||
/// Keep those pages as editable, absolutely positioned text boxes. Every other page, including
|
||||
/// one with a logo or a big title that sits clear of the text, flows as paragraphs and tables.
|
||||
pub(crate) fn positioned(page: &Page) -> bool {
|
||||
if page.blocks.iter().any(|b| b.rotation.abs() > 0.1) {
|
||||
return true;
|
||||
}
|
||||
let body = body_size(std::slice::from_ref(page)).max(1.0);
|
||||
let overlays = page
|
||||
.images
|
||||
.iter()
|
||||
.map(|im| (im.rect, None))
|
||||
.chain(page.blocks.iter().enumerate().filter(|(_, b)| b.size >= 2.0 * body).map(|(i, b)| (b.rect, Some(i))));
|
||||
// Bound the pairwise test on hostile pages (many overlays times many blocks): past the
|
||||
// budget, keep the default flowing layout.
|
||||
let mut budget: usize = 1_000_000;
|
||||
for (r, own) in overlays {
|
||||
for (i, b) in page.blocks.iter().enumerate() {
|
||||
if budget == 0 {
|
||||
return false;
|
||||
}
|
||||
budget -= 1;
|
||||
if Some(i) != own && overlaps(r, b.rect) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether two [x0, y0, x1, y1] boxes share more than a hairline (0.5 pt each way); boxes that
|
||||
/// only touch, or hostile non-finite coordinates, do not count.
|
||||
fn overlaps(a: [f64; 4], b: [f64; 4]) -> bool {
|
||||
let w = a[2].min(b[2]) - a[0].max(b[0]);
|
||||
let h = a[3].min(b[3]) - a[1].max(b[1]);
|
||||
w.is_finite() && h.is_finite() && w > 0.5 && h > 0.5
|
||||
}
|
||||
|
||||
/// Bound every value written into a shape's position and size, including hostile PDF coordinates.
|
||||
fn layout_number(n: f64) -> f64 {
|
||||
if n.is_finite() { n.clamp(-1584.0, 1584.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The stacking order (`Float::z`, higher on top) of watermark-sized text, which is behind
|
||||
/// everything, of the page's pictures, over it, and of its other text, over both.
|
||||
const Z_WATERMARK: u32 = 1;
|
||||
const Z_PICTURE: u32 = 1 << 20;
|
||||
const Z_TEXT: u32 = 1 << 21;
|
||||
|
||||
/// A page that can't flow: one 1 pt paragraph anchors its text boxes and pictures, placed on the
|
||||
/// page. Shapes never reserve body space, so even a page-sized watermark cannot push the text
|
||||
/// after it onto another page.
|
||||
fn positioned_page<'a>(b: &mut Builder<'a>, page: &'a Page) {
|
||||
let mut anchor = Paragraph::new();
|
||||
anchor.props = exact_1pt();
|
||||
let body = body_size(std::slice::from_ref(page)).max(1.0);
|
||||
// The text boxes in reading order, which a screen reader follows; the file's block order isn't
|
||||
// the reading order.
|
||||
let blocks = reading_order(page, page.blocks.iter().map(|bl| (bl.rect, bl.size, bl)).collect());
|
||||
for (i, bl) in blocks.into_iter().enumerate() {
|
||||
let rotation = layout_number(-bl.rotation).rem_euclid(360.0);
|
||||
let (sin, cos) = rotation.to_radians().sin_cos();
|
||||
let (bw, bh) = (layout_number(bl.rect[2] - bl.rect[0]).max(1.0), layout_number(bl.rect[3] - bl.rect[1]).max(1.0));
|
||||
let h = if bl.rotation.abs() > 0.1 { layout_number(bl.size).max(1.0) } else { bh };
|
||||
// Recover the unrotated width from the axis-aligned box. Use the larger axis so quarter
|
||||
// turns and 45-degree watermarks do not divide by (nearly) zero.
|
||||
let w = if bl.rotation.abs() <= 0.1 {
|
||||
bw
|
||||
} else if cos.abs() >= sin.abs() {
|
||||
(bw - h * sin.abs()) / cos.abs()
|
||||
} else {
|
||||
(bh - h * cos.abs()) / sin.abs()
|
||||
};
|
||||
let w = layout_number(w).max(1.0);
|
||||
let (x, y) = (layout_number(bl.rect[0] + (bw - w) / 2.0), layout_number(page.height - bl.rect[3] + (bh - h) / 2.0));
|
||||
let mut p = Paragraph::new();
|
||||
p.props = ParaProps { space_before: Some(0.0), space_after: Some(0.0), ..ParaProps::default() };
|
||||
push_text(&mut p, &bl.text, chr(bl.size, bl.bold, bl.italic, bl.color));
|
||||
let story = b.doc.add_part(PartKind::TextBox, vec![craft_wordmodel::para_block(p)]);
|
||||
if let Some(part) = b.doc.parts.get_mut(&story) {
|
||||
// No inset, and the box grows to fit its text.
|
||||
part.body.inset = Some([0; 4]);
|
||||
part.body.auto_fit = true;
|
||||
}
|
||||
// Each layer keeps to its range, however many blocks a hostile page has.
|
||||
let order = u32::try_from(i).unwrap_or(u32::MAX).min(Z_PICTURE - Z_WATERMARK - 1);
|
||||
let watermark = bl.size >= 2.0 * body;
|
||||
let float = Float {
|
||||
wrap: if watermark { Wrap::BehindText } else { Wrap::InFrontOfText },
|
||||
h_rel: Anchor::Page,
|
||||
v_rel: Anchor::Page,
|
||||
x: x as f32,
|
||||
y: y as f32,
|
||||
rot: rotation as f32,
|
||||
z: if watermark { Z_WATERMARK } else { Z_TEXT }.saturating_add(order),
|
||||
..Float::default()
|
||||
};
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: w as f32,
|
||||
h: h as f32,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float,
|
||||
story: Some(story),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
anchor.push_object(shape, &CharProps::default());
|
||||
}
|
||||
for (n, im) in page.images.iter().enumerate() {
|
||||
let Some(media) = b.add_media(im) else { continue };
|
||||
let (w, h) = (layout_number(im.size[0]).max(1.0), layout_number(im.size[1]).max(1.0));
|
||||
let (x, y) = (layout_number((im.rect[0] + im.rect[2] - w) / 2.0), layout_number(page.height - (im.rect[1] + im.rect[3] + h) / 2.0));
|
||||
let rotation = layout_number(-im.rotation).rem_euclid(360.0);
|
||||
let order = u32::try_from(n).unwrap_or(0).min(Z_TEXT - Z_PICTURE - 1);
|
||||
let float = Float {
|
||||
wrap: Wrap::BehindText,
|
||||
h_rel: Anchor::Page,
|
||||
v_rel: Anchor::Page,
|
||||
x: x as f32,
|
||||
y: y as f32,
|
||||
rot: rotation as f32,
|
||||
z: Z_PICTURE + order,
|
||||
..Float::default()
|
||||
};
|
||||
let pic =
|
||||
InlineObject::Image { media, w: w as f32, h: h as f32, alt: String::new(), float, crop: [0.0; 4], fx: Default::default(), ole: None };
|
||||
anchor.push_object(pic, &CharProps::default());
|
||||
}
|
||||
b.body.push(Block::Para(anchor));
|
||||
}
|
||||
|
||||
/// The pages as a Word document: a page that can't flow ([`positioned`]) keeps its layout as
|
||||
/// positioned text boxes and pictures, and the others flow as paragraphs, tables and pictures.
|
||||
/// Each page is a section of its own size, and its headings are told from its own body size.
|
||||
pub(crate) fn word_doc(pages: &[Page], meta: &Meta) -> Document {
|
||||
let mut b = Builder::new(pages, meta);
|
||||
let mut last = SectionProps::default();
|
||||
for (i, page) in pages.iter().enumerate() {
|
||||
let sec = section(page);
|
||||
if positioned(page) {
|
||||
positioned_page(&mut b, page);
|
||||
} else {
|
||||
for it in items(std::slice::from_ref(page)) {
|
||||
b.flow(it, &sec);
|
||||
}
|
||||
}
|
||||
if i + 1 < pages.len() {
|
||||
b.end_page(sec);
|
||||
} else {
|
||||
last = sec;
|
||||
}
|
||||
}
|
||||
b.finish(last)
|
||||
}
|
||||
@@ -20,13 +20,14 @@ mod as_docx;
|
||||
mod as_html;
|
||||
mod as_markdown;
|
||||
mod as_rtf;
|
||||
mod as_word;
|
||||
mod clip;
|
||||
mod flow;
|
||||
mod layout;
|
||||
|
||||
pub(crate) use as_docx::hex;
|
||||
#[cfg(test)]
|
||||
use as_docx::{MAX_MEDIA, docx_table};
|
||||
use as_docx::MAX_MEDIA;
|
||||
pub(crate) use as_docx::hex;
|
||||
pub use as_docx::{docx, docx_with_language};
|
||||
pub(crate) use as_html::esc;
|
||||
#[cfg(test)]
|
||||
@@ -35,7 +36,7 @@ pub use as_html::{html, html_simple, html_simple_with_language, html_with_langua
|
||||
pub use as_markdown::markdown;
|
||||
#[cfg(test)]
|
||||
use as_markdown::{emphasis, paragraph};
|
||||
pub use as_rtf::rtf;
|
||||
pub use as_rtf::{rtf, rtf_with_title};
|
||||
pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family};
|
||||
#[cfg(test)]
|
||||
use flow::list_item;
|
||||
|
||||
+371
-109
@@ -120,10 +120,14 @@ fn docx_is_a_word_package() {
|
||||
|
||||
#[test]
|
||||
fn word_does_not_invent_borders_for_aligned_invoice_fields() {
|
||||
let xml = part(&docx(&[table_page()], "Invoice"), "word/document.xml");
|
||||
assert!(xml.contains("<w:tbl>"));
|
||||
assert!(!xml.contains("w:val=\"single\""), "text alignment is not evidence of a border: {xml}");
|
||||
assert!(xml.contains("<w:insideH w:val=\"nil\"/>"));
|
||||
let tables = docx_tables(&docx(&[table_page()], "Invoice"));
|
||||
assert_eq!(tables.len(), 1);
|
||||
let single = |b: &Option<craft_wordmodel::props::Border>| b.is_some_and(|b| b.style == craft_wordmodel::props::BorderStyle::Single);
|
||||
let cells = tables[0].rows.iter().flat_map(|r| &r.cells).filter_map(|c| c.props.borders);
|
||||
let table = tables[0].props.borders.into_iter();
|
||||
for b in table.chain(cells) {
|
||||
assert!(![b.top, b.left, b.bottom, b.right, b.between, b.inside_v].iter().any(single), "text alignment is not evidence of a border: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -141,28 +145,71 @@ fn word_table_cell_widths_follow_the_columns_they_span() {
|
||||
],
|
||||
ruled: None,
|
||||
};
|
||||
let xml = docx_table(&table);
|
||||
assert!(xml.contains("<w:gridCol w:w=\"1000\"/><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/>"), "{xml}");
|
||||
let widths: Vec<Vec<&str>> =
|
||||
xml.split("<w:tr>").skip(1).map(|row| row.split("<w:tcW w:w=\"").skip(1).map(|cell| cell.split('"').next().unwrap()).collect()).collect();
|
||||
assert_eq!(widths, vec![vec!["1000", "2000", "3000"], vec!["1000", "5000"], vec!["3000", "3000"], vec!["6000"], vec!["1000", "0", "0"]]);
|
||||
let t = crate::as_word::table(&table);
|
||||
assert_eq!(t.grid, [50.0, 100.0, 150.0]);
|
||||
let widths: Vec<Vec<f32>> = t.rows.iter().map(|r| r.cells.iter().map(|c| c.props.width.unwrap_or(0.0)).collect()).collect();
|
||||
// A short row is padded to the grid with cells as wide as the columns they fill.
|
||||
assert_eq!(widths, vec![vec![50.0, 100.0, 150.0], vec![50.0, 250.0], vec![150.0, 150.0], vec![300.0], vec![50.0, 100.0, 150.0]]);
|
||||
}
|
||||
|
||||
/// The tables a Word document holds, read back through craft-docx.
|
||||
fn docx_tables(d: &[u8]) -> Vec<craft_wordmodel::Table> {
|
||||
craft_docx::read(d)
|
||||
.unwrap()
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.clone()) } else { None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The paragraphs of a document's body (not inside tables).
|
||||
fn body_paragraphs(doc: &craft_wordmodel::Document) -> Vec<&craft_wordmodel::Paragraph> {
|
||||
doc.body.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// The objects in the body's paragraphs, in order.
|
||||
fn body_objects(doc: &craft_wordmodel::Document) -> Vec<&craft_wordmodel::InlineObject> {
|
||||
body_paragraphs(doc).into_iter().flat_map(|p| &p.objects).collect()
|
||||
}
|
||||
|
||||
/// A shape's text, from the story it holds.
|
||||
fn shape_text(doc: &craft_wordmodel::Document, o: &craft_wordmodel::InlineObject) -> String {
|
||||
let craft_wordmodel::InlineObject::Shape { story: Some(id), .. } = o else { return String::new() };
|
||||
doc.parts
|
||||
.get(id)
|
||||
.map(|part| part.blocks.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A floating object's placement.
|
||||
fn float_of(o: &craft_wordmodel::InlineObject) -> Option<&craft_wordmodel::para::Float> {
|
||||
match o {
|
||||
craft_wordmodel::InlineObject::Shape { float, .. } | craft_wordmodel::InlineObject::Image { float, .. } => Some(float),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_keeps_a_page_with_a_clear_image_and_big_title_in_flow() {
|
||||
// page() has a picture between paragraphs and a 24 pt title over 11 pt body text, but
|
||||
// nothing overlaps: it must stay flowing paragraphs with the image inline.
|
||||
let xml = part(&docx(&[page()], "Report"), "word/document.xml");
|
||||
assert!(!xml.contains("position:absolute"), "nothing overlaps, so nothing floats: {xml}");
|
||||
assert!(xml.contains("<wp:inline>"), "the picture stays inline: {xml}");
|
||||
assert!(xml.contains("<w:pStyle w:val=\"Heading1\"/>"), "the title stays a heading: {xml}");
|
||||
let (title, body) = (xml.find(">Annual Report</w:t>"), xml.find(">Body text after the picture"));
|
||||
assert!(title.is_some() && body.is_some() && title < body, "reading order kept: {xml}");
|
||||
let doc = craft_docx::read(&docx(&[page()], "Report")).unwrap();
|
||||
let objects = body_objects(&doc);
|
||||
assert!(objects.iter().all(|o| !matches!(o, craft_wordmodel::InlineObject::Shape { .. })), "nothing overlaps, so nothing floats: {objects:?}");
|
||||
assert!(
|
||||
objects.iter().any(|o| matches!(o, craft_wordmodel::InlineObject::Image { float, .. } if float.wrap == craft_wordmodel::para::Wrap::Inline)),
|
||||
"the picture stays inline: {objects:?}"
|
||||
);
|
||||
let paras = body_paragraphs(&doc);
|
||||
let title = paras.iter().position(|p| p.plain_text() == "Annual Report");
|
||||
let body = paras.iter().position(|p| p.plain_text().starts_with("Body text after the picture"));
|
||||
assert_eq!(title.and_then(|i| paras[i].props.style.as_deref()), Some("Heading1"), "the title stays a heading");
|
||||
assert!(title.is_some() && body.is_some() && title < body, "reading order kept");
|
||||
// The same page with the picture moved over the body text floats.
|
||||
let mut over = page();
|
||||
over.images[0].rect = [72.0, 380.0, 272.0, 530.0];
|
||||
let xml = part(&docx(&[over], "Report"), "word/document.xml");
|
||||
assert!(xml.contains("position:absolute"), "an image over text floats: {xml}");
|
||||
let doc = craft_docx::read(&docx(&[over], "Report")).unwrap();
|
||||
assert!(body_objects(&doc).iter().any(|o| matches!(o, craft_wordmodel::InlineObject::Shape { .. })), "an image over text floats the page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -179,18 +226,23 @@ fn word_overlap_does_not_consume_invoice_body_space() {
|
||||
space_around: [false; 2],
|
||||
});
|
||||
p.images = page().images;
|
||||
let xml = part(&docx(&[p], "Invoice"), "word/document.xml");
|
||||
assert!(xml.contains("position:absolute"), "overlapping text must float: {xml}");
|
||||
assert!(!xml.contains("<wp:inline>"), "images must not displace invoice text");
|
||||
assert!(!xml.contains("<w:tbl>"), "the source text boxes must keep their positions");
|
||||
assert_eq!(xml.matches(">DRAFT</w:t>").count(), 1);
|
||||
assert_eq!(xml.matches("w:type=\"page\"").count(), 0);
|
||||
assert!(xml.contains("margin-left:72.000pt;margin-top:160.000pt"), "Meter field keeps its source position: {xml}");
|
||||
let watermark = xml.split(">DRAFT</w:t>").next().unwrap().rsplit("<v:rect ").next().unwrap();
|
||||
assert!(watermark.contains("z-index:-2"), "watermark is behind foreground graphics");
|
||||
// The picture is a DrawingML anchor behind the text (a VML rectangle shows no picture in Word).
|
||||
assert!(!xml.contains("<v:imagedata"), "{xml}");
|
||||
assert!(xml.contains("<wp:anchor ") && xml.contains("behindDoc=\"1\"") && xml.contains("<a:blip r:embed=\"rIdImg1\"/>"), "{xml}");
|
||||
let d = docx(&[p], "Invoice");
|
||||
let doc = craft_docx::read(&d).unwrap();
|
||||
use craft_wordmodel::para::{Anchor, Wrap};
|
||||
assert!(doc.body.iter().all(|b| !matches!(&**b, craft_wordmodel::Block::Table(_))), "the source text boxes keep their positions");
|
||||
let objects = body_objects(&doc);
|
||||
let shape = |text: &str| objects.iter().copied().find(|o| shape_text(&doc, o) == text);
|
||||
let draft = shape("DRAFT").and_then(float_of).expect("the watermark is a text box");
|
||||
assert_eq!(objects.iter().filter(|o| shape_text(&doc, o) == "DRAFT").count(), 1);
|
||||
let meter = shape("Meter").and_then(float_of).expect("Meter is a text box");
|
||||
assert_eq!((meter.h_rel, meter.v_rel), (Anchor::Page, Anchor::Page));
|
||||
assert_eq!((meter.x, meter.y), (72.0, 160.0), "the Meter field keeps its source position");
|
||||
assert_eq!(meter.wrap, Wrap::InFrontOfText);
|
||||
assert!(!body_paragraphs(&doc).iter().any(|p| p.text.contains(craft_wordmodel::para::PAGE_BREAK)), "no page breaks");
|
||||
// The watermark is behind everything, and the picture, behind the text too, is drawn over it.
|
||||
let picture = objects.iter().copied().find(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. })).and_then(float_of).expect("the picture");
|
||||
assert_eq!((draft.wrap, picture.wrap), (Wrap::BehindText, Wrap::BehindText), "images must not displace invoice text");
|
||||
assert!(draft.z < picture.z && picture.z < meter.z, "{} < {} < {}", draft.z, picture.z, meter.z);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -200,12 +252,18 @@ fn word_rotated_pages_keep_separate_page_sizes_and_unique_shapes() {
|
||||
let mut second = p.clone();
|
||||
second.width = 400.0;
|
||||
second.height = 500.0;
|
||||
let xml = part(&docx(&[p, second], "Two invoices"), "word/document.xml");
|
||||
assert!(xml.contains("rotation:315.000"), "PDF y-up becomes Word y-down");
|
||||
assert_eq!(xml.matches("<w:sectPr>").count(), 2);
|
||||
assert!(xml.contains("<w:pgSz w:w=\"8000\" w:h=\"10000\"/>"));
|
||||
assert_eq!(xml.matches("id=\"Text1\"").count(), 1);
|
||||
assert_eq!(xml.matches(">Meter</w:t>").count(), 2);
|
||||
let d = docx(&[p, second], "Two invoices");
|
||||
let doc = craft_docx::read(&d).unwrap();
|
||||
let meters: Vec<_> = body_objects(&doc).into_iter().filter(|o| shape_text(&doc, o) == "Meter").collect();
|
||||
assert_eq!(meters.len(), 2);
|
||||
assert!(meters.iter().all(|o| float_of(o).is_some_and(|f| (f.rot - 315.0).abs() < 0.01)), "PDF y-up becomes Word y-down");
|
||||
let sizes: Vec<(f32, f32)> = doc.sections().iter().map(|(_, s)| (s.page_w, s.page_h)).collect();
|
||||
assert_eq!(sizes, [(612.0, 792.0), (400.0, 500.0)]);
|
||||
// Every drawing has an id of its own.
|
||||
let xml = part(&d, "word/document.xml");
|
||||
let ids: Vec<&str> = xml.split("<wp:docPr id=\"").skip(1).filter_map(|s| s.split('"').next()).collect();
|
||||
let unique: std::collections::HashSet<&str> = ids.iter().copied().collect();
|
||||
assert!(!ids.is_empty() && unique.len() == ids.len(), "{ids:?}");
|
||||
}
|
||||
|
||||
/// #2992: pages that share a background colour get it as the Word document's page colour
|
||||
@@ -214,11 +272,10 @@ fn word_rotated_pages_keep_separate_page_sizes_and_unique_shapes() {
|
||||
fn docx_keeps_a_shared_page_background() {
|
||||
let teal = Page { background: Some([0.0, 0.5, 0.5]), ..page() };
|
||||
let zip = docx(&[teal.clone(), teal.clone()], "Teal");
|
||||
let xml = part(&zip, "word/document.xml");
|
||||
assert!(xml.contains("<w:background w:color=\"008080\"/><w:body>"), "{xml}");
|
||||
assert_eq!(craft_docx::read(&zip).unwrap().settings.page_color, Some(craft_wordmodel::Rgb(0, 128, 128)));
|
||||
// Word shows the colour only when the settings say so.
|
||||
assert!(part(&zip, "word/document.xml").contains("<w:background w:color=\"008080\""));
|
||||
assert!(part(&zip, "word/settings.xml").contains("<w:displayBackgroundShape/>"));
|
||||
assert!(part(&zip, "[Content_Types].xml").contains("/word/settings.xml"));
|
||||
assert!(part(&zip, "word/_rels/document.xml.rels").contains("Target=\"settings.xml\""));
|
||||
let other = Page { background: Some([1.0, 0.0, 0.0]), ..page() };
|
||||
for (pages, why) in [
|
||||
(vec![teal.clone(), other], "different colours"),
|
||||
@@ -227,8 +284,8 @@ fn docx_keeps_a_shared_page_background() {
|
||||
(vec![page()], "none"),
|
||||
] {
|
||||
let zip = docx(&pages, "Plain");
|
||||
assert_eq!(craft_docx::read(&zip).unwrap().settings.page_color, None, "{why}");
|
||||
assert!(!part(&zip, "word/document.xml").contains("<w:background"), "{why}");
|
||||
assert!(!zip.windows(b"word/settings.xml".len()).any(|w| w == b"word/settings.xml"), "{why}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,24 +312,30 @@ pub(crate) fn part(zip: &[u8], name: &str) -> String {
|
||||
#[test]
|
||||
fn word_and_html_take_the_documents_language() {
|
||||
let pages = [page()];
|
||||
let styles = |lang| part(&docx_with_language(&pages, "Report", lang), "word/styles.xml");
|
||||
let defaults = |lang: &str| format!("<w:docDefaults><w:rPrDefault><w:rPr>{lang}</w:rPr></w:rPrDefault></w:docDefaults>");
|
||||
assert!(styles(Some("bg-BG")).contains(&defaults("<w:lang w:val=\"bg-BG\"/>")), "{}", styles(Some("bg-BG")));
|
||||
assert!(styles(Some(" en-GB ")).contains("<w:lang w:val=\"en-GB\"/>"), "the tag is trimmed");
|
||||
assert!(styles(Some("zh-Hant-TW")).contains(&defaults("<w:lang w:eastAsia=\"zh-Hant-TW\"/>")), "East Asian text");
|
||||
assert!(styles(Some("ja")).contains("<w:lang w:eastAsia=\"ja\"/>"), "East Asian text");
|
||||
assert!(styles(Some("ar-EG")).contains(&defaults("<w:lang w:bidi=\"ar-EG\"/>")), "right-to-left text");
|
||||
assert!(styles(Some("HE")).contains("<w:lang w:bidi=\"HE\"/>"), "right-to-left text");
|
||||
// The document default languages Word reads back: (Latin, East Asian, right-to-left).
|
||||
let langs = |lang| {
|
||||
let c = craft_docx::read(&docx_with_language(&pages, "Report", lang)).unwrap().styles.default_chr.clone();
|
||||
(c.lang, c.lang_ea, c.lang_bidi)
|
||||
};
|
||||
let latin = |t: &str| (Some(t.to_string()), None, None);
|
||||
let east_asian = |t: &str| (None, Some(t.to_string()), None);
|
||||
let bidi = |t: &str| (None, None, Some(t.to_string()));
|
||||
assert_eq!(langs(Some("bg-BG")), latin("bg-BG"));
|
||||
assert_eq!(langs(Some(" en-GB ")), latin("en-GB"), "the tag is trimmed");
|
||||
assert_eq!(langs(Some("zh-Hant-TW")), east_asian("zh-Hant-TW"), "East Asian text");
|
||||
assert_eq!(langs(Some("ja")), east_asian("ja"), "East Asian text");
|
||||
assert_eq!(langs(Some("ar-EG")), bidi("ar-EG"), "right-to-left text");
|
||||
assert_eq!(langs(Some("HE")), bidi("HE"), "right-to-left text");
|
||||
// A script subtag decides over the language; private use names no script.
|
||||
assert!(styles(Some("pa-Arab-PK")).contains("<w:lang w:bidi=\"pa-Arab-PK\"/>"), "Punjabi in Arabic script");
|
||||
assert!(styles(Some("sr-Latn")).contains("<w:lang w:val=\"sr-Latn\"/>"), "Serbian in Latin script");
|
||||
assert!(styles(Some("zh-Latn")).contains("<w:lang w:val=\"zh-Latn\"/>"), "Chinese in Latin script");
|
||||
assert!(styles(Some("en-x-arab")).contains("<w:lang w:val=\"en-x-arab\"/>"), "private use");
|
||||
assert!(styles(Some("az-Latn-x-arab")).contains("<w:lang w:val=\"az-Latn-x-arab\"/>"), "private use");
|
||||
assert_eq!(langs(Some("pa-Arab-PK")), bidi("pa-Arab-PK"), "Punjabi in Arabic script");
|
||||
assert_eq!(langs(Some("sr-Latn")), latin("sr-Latn"), "Serbian in Latin script");
|
||||
assert_eq!(langs(Some("zh-Latn")), latin("zh-Latn"), "Chinese in Latin script");
|
||||
assert_eq!(langs(Some("en-x-arab")), latin("en-x-arab"), "private use");
|
||||
assert_eq!(langs(Some("az-Latn-x-arab")), latin("az-Latn-x-arab"), "private use");
|
||||
assert!(html_with_language(&pages, "Report", Some("bg-BG")).starts_with("<!DOCTYPE html>\n<html lang=\"bg-BG\">\n"));
|
||||
// A tag longer than 35 characters is still a tag.
|
||||
let long = "en-US-u-ca-gregory-nu-latn-co-phonebk";
|
||||
assert!(styles(Some(long)).contains(&format!("<w:lang w:val=\"{long}\"/>")), "{long}");
|
||||
assert_eq!(langs(Some(long)), latin(long), "{long}");
|
||||
assert!(html_with_language(&pages, "Report", Some(long)).contains(&format!("<html lang=\"{long}\">")), "{long}");
|
||||
let too_long = format!("en{}", "-abcdefgh".repeat(29));
|
||||
// Private use takes one-character subtags.
|
||||
@@ -296,7 +359,7 @@ fn word_and_html_take_the_documents_language() {
|
||||
Some("1a-BG"),
|
||||
Some("\u{431}\u{433}-BG"),
|
||||
] {
|
||||
assert!(docx_with_language(&pages, "Report", lang) == docx(&pages, "Report"), "{lang:?}");
|
||||
assert_eq!(langs(lang), (None, None, None), "{lang:?}");
|
||||
assert_eq!(html_with_language(&pages, "Report", lang), html(&pages, "Report"), "{lang:?}");
|
||||
assert_eq!(html_simple_with_language(&pages, "Report", lang), html_simple(&pages, "Report"), "{lang:?}");
|
||||
}
|
||||
@@ -320,16 +383,19 @@ fn word_opens_text_with_control_characters_and_long_pages() {
|
||||
rotation: 0.0,
|
||||
space_around: [false; 2],
|
||||
});
|
||||
let xml = part(&docx(&[p.clone()], "Receipt\u{1}"), "word/document.xml");
|
||||
assert!(xml.contains(">Total 4.50\tGBP</w:t>"), "{xml}");
|
||||
let d = docx(&[p.clone()], "Receipt\u{1}");
|
||||
let xml = part(&d, "word/document.xml");
|
||||
assert!(!xml.chars().any(|c| !allowed(c)));
|
||||
assert!(xml.contains("<w:pgSz w:w=\"12240\" w:h=\"31680\"/>"), "clamped to 22 in: {xml}");
|
||||
assert!(xml.contains("<w:sz w:val=\"24\"/>"), "a non-finite size falls back to 12 pt");
|
||||
let doc = craft_docx::read(&d).unwrap();
|
||||
let total = body_paragraphs(&doc).into_iter().find(|p| p.plain_text().starts_with("Total")).expect("the receipt line");
|
||||
assert_eq!(total.plain_text(), "Total 4.50\tGBP");
|
||||
assert_eq!(total.runs.first().and_then(|r| r.props.size), Some(12.0), "a non-finite size falls back to 12 pt");
|
||||
assert_eq!(doc.last_section.page_h, 1584.0, "clamped to 22 in");
|
||||
assert!(rtf(&[p]).contains("Total 4.50\\tab GBP"));
|
||||
// A narrow page keeps room for text: margins shrink.
|
||||
let narrow = Page { width: 100.0, height: 200.0, ..page() };
|
||||
let xml = part(&docx(&[narrow], "Narrow"), "word/document.xml");
|
||||
assert!(xml.contains("<w:pgMar w:top=\"500\" w:right=\"250\" w:bottom=\"500\" w:left=\"250\""), "{xml}");
|
||||
let s = craft_docx::read(&docx(&[narrow], "Narrow")).unwrap().last_section;
|
||||
assert_eq!([s.margin_top, s.margin_right, s.margin_bottom, s.margin_left], [25.0, 12.5, 25.0, 12.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,50 +454,85 @@ fn rtf_escapes_and_sizes() {
|
||||
space_around: [false; 2],
|
||||
});
|
||||
let r = rtf(&[p]);
|
||||
assert!(r.starts_with("{\\rtf1") && r.ends_with('}'));
|
||||
assert!(r.starts_with("{\\rtf1") && r.trim_end().ends_with('}'));
|
||||
assert!(r.contains("Caf\\u233? \\{x\\}"), "escaped: {r}");
|
||||
let runs: Vec<_> = rtf_paras(&r).into_iter().flatten().collect();
|
||||
assert!(runs.contains(&("Annual Report".into(), true, false, Some(48))), "{runs:?}");
|
||||
assert!(runs.contains(&("Café {x}".into(), false, true, Some(20))), "{runs:?}");
|
||||
}
|
||||
|
||||
/// A page break starts the next page's first paragraph, and stands in a paragraph of its own
|
||||
/// before a table, rather than in the table's first cell.
|
||||
#[test]
|
||||
fn rtf_page_breaks_stay_out_of_tables() {
|
||||
let r = rtf(&[page(), table_page(), page()]);
|
||||
let back = craft_rtf::read(r.as_bytes()).unwrap();
|
||||
let first_cell = back.blocks.iter().find_map(|b| match b {
|
||||
craft_rtf::Block::Table(t) => t.rows.first().and_then(|row| row.first()).map(|c| c.paras.iter().map(|p| p.text()).collect::<String>()),
|
||||
craft_rtf::Block::Para(_) => None,
|
||||
});
|
||||
assert_eq!(first_cell.as_deref(), Some("Meter"), "{r}");
|
||||
let texts: Vec<String> = back.blocks.iter().map(|b| if let craft_rtf::Block::Para(p) = b { p.text() } else { "<table>".into() }).collect();
|
||||
let table = texts.iter().position(|t| t == "<table>");
|
||||
assert_eq!(table.and_then(|i| i.checked_sub(1)).and_then(|i| texts.get(i)).map(String::as_str), Some("\u{000C}"), "{texts:?}");
|
||||
assert_eq!(texts.iter().filter(|t| t.starts_with('\u{000C}')).count(), 2, "one break before each later page: {texts:?}");
|
||||
/// The RTF read back into the word model: each section's page size (points) and the text of its
|
||||
/// blocks, tables as `<table:first cell>`.
|
||||
fn rtf_sections(r: &str) -> Vec<([f32; 2], Vec<String>)> {
|
||||
let doc = craft_rtf::doc::import(r.as_bytes()).unwrap();
|
||||
let mut out: Vec<([f32; 2], Vec<String>)> = Vec::new();
|
||||
let mut texts = Vec::new();
|
||||
for b in &doc.body {
|
||||
match &**b {
|
||||
craft_wordmodel::Block::Para(p) => {
|
||||
if !p.plain_text().is_empty() || !p.objects.is_empty() {
|
||||
texts.push(if p.objects.is_empty() { p.plain_text() } else { "<picture>".into() });
|
||||
}
|
||||
if let Some(s) = &p.section {
|
||||
out.push(([s.page_w, s.page_h], std::mem::take(&mut texts)));
|
||||
}
|
||||
}
|
||||
craft_wordmodel::Block::Table(t) => {
|
||||
let first = t
|
||||
.rows
|
||||
.first()
|
||||
.and_then(|r| r.cells.first())
|
||||
.map(|c| {
|
||||
c.blocks
|
||||
.iter()
|
||||
.filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None })
|
||||
.collect::<String>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
texts.push(format!("<table:{}>", first.trim()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(([doc.last_section.page_w, doc.last_section.page_h], texts));
|
||||
out
|
||||
}
|
||||
|
||||
/// Empty and image-only pages still occupy a page when pictures are omitted from RTF.
|
||||
/// Each page is a section of its own, so it starts a new page, and a table on a page is in that
|
||||
/// page's section rather than after a break character in its first cell.
|
||||
#[test]
|
||||
fn rtf_preserves_breaks_for_pages_without_text() {
|
||||
fn rtf_pages_are_sections_and_tables_stay_on_theirs() {
|
||||
let r = rtf(&[page(), table_page(), page()]);
|
||||
let sections = rtf_sections(&r);
|
||||
assert_eq!(sections.len(), 3, "{sections:?}");
|
||||
assert!(sections[1].1.first().is_some_and(|t| t == "<table:Meter>"), "{sections:?}");
|
||||
assert!(!r.contains("\\page"), "sections break the pages: {r}");
|
||||
}
|
||||
|
||||
/// Empty and image-only pages still occupy a page; each keeps its own size.
|
||||
#[test]
|
||||
fn rtf_keeps_pages_without_text() {
|
||||
let mut blank = page();
|
||||
blank.blocks.clear();
|
||||
blank.images.clear();
|
||||
blank.rules.clear();
|
||||
let mut image_only = page();
|
||||
image_only.blocks.clear();
|
||||
let mut small = blank.clone();
|
||||
small.width = 400.0;
|
||||
small.height = 500.0;
|
||||
for pages in [
|
||||
vec![blank.clone(), blank.clone(), page()],
|
||||
vec![page(), blank.clone(), blank.clone()],
|
||||
vec![page(), blank.clone(), blank.clone(), table_page()],
|
||||
vec![blank.clone(), blank.clone(), blank],
|
||||
vec![blank.clone(), blank.clone(), blank.clone()],
|
||||
vec![page(), image_only.clone(), image_only.clone(), page()],
|
||||
vec![page(), image_only],
|
||||
vec![page(), small, blank],
|
||||
] {
|
||||
let r = rtf(&pages);
|
||||
let breaks = rtf_paras(&r).iter().flatten().map(|run| run.0.matches(craft_rtf::PAGE_BREAK).count()).sum::<usize>();
|
||||
assert_eq!(breaks, pages.len() - 1, "{r}");
|
||||
let sizes: Vec<[f32; 2]> = rtf_sections(&r).iter().map(|s| s.0).collect();
|
||||
let want: Vec<[f32; 2]> = pages.iter().map(|p| [p.width as f32, p.height as f32]).collect();
|
||||
assert_eq!(sizes, want, "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -493,16 +594,19 @@ fn grid_text_becomes_a_real_table_in_every_format() {
|
||||
assert!(d.windows(b"word/document.xml".len()).any(|w| w == b"word/document.xml"));
|
||||
let (tables, _) = tables(&p.blocks, &p.rules);
|
||||
assert_eq!(tables.len(), 1);
|
||||
let table_xml = docx_table(&tables[0]);
|
||||
assert!(table_xml.contains("<w:tblGrid>"));
|
||||
assert!(table_xml.contains("<w:gridSpan w:val=\"2\"/>"), "{table_xml}");
|
||||
assert_eq!(table_xml.matches("<w:tr>").count(), 4);
|
||||
let read = docx_tables(&d);
|
||||
assert_eq!(read.len(), 1, "{read:?}");
|
||||
assert_eq!(read[0].grid.len(), 3, "a three-column grid");
|
||||
assert_eq!(read[0].rows.len(), 4);
|
||||
assert!(read[0].rows.iter().any(|r| r.cells.first().is_some_and(|c| c.props.span == 2)), "Totals spans two columns: {:?}", read[0]);
|
||||
|
||||
let r = rtf(std::slice::from_ref(&p));
|
||||
assert!(r.contains("\\trowd"), "{r}");
|
||||
assert_eq!(r.matches("\\row").count(), 4);
|
||||
// Each cell ends at its last column's right edge; "Totals" spans two columns, so it ends at
|
||||
// the second of the three.
|
||||
// Each cell ends at its last column's right edge, measured from the left margin (`\cellx`):
|
||||
// the columns start at x = 72, 232 and 392 and the table ends at 496, so 160, 160 and 104 pt
|
||||
// wide. "Totals" spans two columns, so it ends at the second edge, and its row is padded to
|
||||
// the grid with an empty cell.
|
||||
let back = craft_rtf::read(r.as_bytes()).unwrap();
|
||||
let rows: Vec<Vec<(i32, String)>> = back
|
||||
.blocks
|
||||
@@ -511,8 +615,8 @@ fn grid_text_becomes_a_real_table_in_every_format() {
|
||||
.flat_map(|t| &t.rows)
|
||||
.map(|row| row.iter().map(|c| (c.right, c.paras.iter().map(|p| p.text()).collect())).collect())
|
||||
.collect();
|
||||
assert_eq!(rows.first().map(|r| r.iter().map(|c| c.0).collect::<Vec<_>>()), Some(vec![4640, 7840, 9920]), "{rows:?}");
|
||||
assert!(rows.contains(&vec![(7840, "Totals".to_string())]), "{rows:?}");
|
||||
assert_eq!(rows.first().map(|r| r.iter().map(|c| c.0).collect::<Vec<_>>()), Some(vec![3200, 6400, 8480]), "{rows:?}");
|
||||
assert!(rows.contains(&vec![(6400, "Totals".to_string()), (8480, String::new())]), "{rows:?}");
|
||||
|
||||
let pt = pptx(std::slice::from_ref(&p), "Bill");
|
||||
assert!(pt.starts_with(b"PK"));
|
||||
@@ -736,17 +840,14 @@ fn word_pictures_resolve_to_media_in_the_package() {
|
||||
p.blocks[0].rect = [72.0, 700.0, 300.0, 760.0];
|
||||
}
|
||||
let zip = docx(&[p], "T");
|
||||
let xml = part(&zip, "word/document.xml");
|
||||
assert_eq!(xml.contains("<wp:anchor "), placed, "{xml}");
|
||||
let rels = part(&zip, "word/_rels/document.xml.rels");
|
||||
let embed = xml.split("r:embed=\"").nth(1).and_then(|r| r.split('"').next()).unwrap();
|
||||
let rel = rels.split(&format!("Id=\"{embed}\"")).nth(1).unwrap();
|
||||
assert!(rel.contains("relationships/image\""), "{rels}");
|
||||
let target = rel.split("Target=\"").nth(1).and_then(|t| t.split('"').next()).unwrap();
|
||||
assert_eq!(target, "media/image1.jpg");
|
||||
assert!(zip.windows(21).any(|w| w == b"word/media/image1.jpg"));
|
||||
assert!(part(&zip, "[Content_Types].xml").contains("Extension=\"jpg\" ContentType=\"image/jpeg\""));
|
||||
assert!(xml.matches("<wp:docPr ").count() == 1 && !xml.contains("<v:imagedata"));
|
||||
let doc = craft_docx::read(&zip).unwrap();
|
||||
let pictures: Vec<_> = body_objects(&doc).into_iter().filter(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. })).collect();
|
||||
assert_eq!(pictures.len(), 1);
|
||||
let craft_wordmodel::InlineObject::Image { media, float, .. } = pictures[0] else { panic!("not a picture") };
|
||||
assert_eq!(float.wrap != craft_wordmodel::para::Wrap::Inline, placed);
|
||||
// The picture resolves to the JPEG's bytes in the package, which has a type for it.
|
||||
assert_eq!(doc.media.get(media).map(|b| b.to_vec()), Some(vec![0xFF, 0xD8, 0xFF, 0xD9]), "{:?}", doc.media.keys().collect::<Vec<_>>());
|
||||
assert!(part(&zip, "[Content_Types].xml").contains("image/jpeg"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -757,8 +858,11 @@ fn word_export_bounds_the_number_of_pictures_and_skips_empty_ones() {
|
||||
p.images = vec![Image { bytes: [].as_slice().into(), ..one.clone() }];
|
||||
p.images.extend(std::iter::repeat_n(one, MAX_MEDIA + 10));
|
||||
let zip = docx(&[p], "T");
|
||||
let rels = part(&zip, "word/_rels/document.xml.rels");
|
||||
assert_eq!(rels.matches("relationships/image\"").count(), MAX_MEDIA);
|
||||
let doc = craft_docx::read(&zip).unwrap();
|
||||
let placed = body_objects(&doc).into_iter().filter(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. })).count();
|
||||
assert_eq!(placed, MAX_MEDIA, "at most MAX_MEDIA pictures, and none for the empty one");
|
||||
// One picture drawn many times is one file in the package.
|
||||
assert_eq!(doc.media.len(), 1);
|
||||
}
|
||||
|
||||
/// The flowing paragraphs of a Word document (table cells left out), each as its runs' text
|
||||
@@ -1134,12 +1238,11 @@ fn a_ruled_table_gets_outer_borders_only_where_the_page_draws_them() {
|
||||
let (found, _) = tables(&blocks, &inside);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].ruled, Some([false; 4]));
|
||||
let xml = docx_table(&found[0]);
|
||||
for edge in ["insideH", "insideV"] {
|
||||
assert!(xml.contains(&format!("<w:{edge} w:val=\"single\"")), "{xml}");
|
||||
}
|
||||
for edge in ["top", "left", "bottom", "right"] {
|
||||
assert!(xml.contains(&format!("<w:{edge} w:val=\"nil\"/>")), "{xml}");
|
||||
let borders = crate::as_word::table(&found[0]).props.borders.unwrap();
|
||||
let single = |b: Option<craft_wordmodel::props::Border>| b.is_some_and(|b| b.style == craft_wordmodel::props::BorderStyle::Single);
|
||||
assert!(single(borders.between) && single(borders.inside_v), "{borders:?}");
|
||||
for edge in [borders.top, borders.left, borders.bottom, borders.right] {
|
||||
assert!(!single(edge), "{borders:?}");
|
||||
}
|
||||
|
||||
let mut ruled_top = inside.clone();
|
||||
@@ -1454,3 +1557,162 @@ fn html_bounds_the_pictures_it_embeds() {
|
||||
assert_eq!(h.matches("<img").count(), MAX_MEDIA);
|
||||
}
|
||||
}
|
||||
|
||||
/// RTF keeps a page's pictures, inline where they sit in the reading order (it left them out).
|
||||
#[test]
|
||||
fn rtf_keeps_pictures() {
|
||||
let r = rtf(&[page()]);
|
||||
assert!(r.contains(r"\pngblip"), "{r}");
|
||||
let doc = craft_rtf::doc::import(r.as_bytes()).unwrap();
|
||||
let pictures = doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None })
|
||||
.flat_map(|p| &p.objects)
|
||||
.filter(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. }))
|
||||
.count();
|
||||
assert_eq!(pictures, 1, "{r}");
|
||||
}
|
||||
|
||||
/// Headings are Word's Heading 1 and 2 styles, which a word processor shows in its outline.
|
||||
#[test]
|
||||
fn rtf_headings_have_heading_styles() {
|
||||
let r = rtf(&[page()]);
|
||||
let doc = craft_rtf::doc::import(r.as_bytes()).unwrap();
|
||||
let heading = doc.body.iter().find_map(|b| match &**b {
|
||||
craft_wordmodel::Block::Para(p) if p.plain_text() == "Annual Report" => Some(p.props.style.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let style = heading.flatten().and_then(|id| doc.styles.styles.iter().find(|s| s.id == id).map(|s| s.para.outline_level));
|
||||
assert_eq!(style, Some(Some(0)), "Annual Report is a level 1 heading: {r}");
|
||||
}
|
||||
|
||||
/// The document's title goes into the RTF's information group, and PdfCraft is named as the
|
||||
/// application that wrote it.
|
||||
#[test]
|
||||
fn rtf_names_the_title_and_pdfcraft() {
|
||||
let r = crate::rtf_with_title(&[page()], "Annual Report");
|
||||
assert_eq!(craft_rtf::doc::import(r.as_bytes()).unwrap().core.title, "Annual Report", "{r}");
|
||||
assert!(r.contains(r"{\*\generator PdfCraft;}") && !r.contains("WordCraft"), "{r}");
|
||||
}
|
||||
|
||||
/// Two tables one under the other stay two tables: in RTF, rows that follow each other are one
|
||||
/// table, so a paragraph keeps them apart.
|
||||
#[test]
|
||||
fn rtf_keeps_tables_that_touch_apart() {
|
||||
// Two grids on one page with nothing between them.
|
||||
let mut one = table_page();
|
||||
one.blocks.retain(|b| !b.text.starts_with("Notes"));
|
||||
let mut lower = one.blocks.clone();
|
||||
for b in &mut lower {
|
||||
b.rect[1] -= 300.0;
|
||||
b.rect[3] -= 300.0;
|
||||
}
|
||||
one.blocks.extend(lower);
|
||||
let r = rtf(std::slice::from_ref(&one));
|
||||
let (found, _) = tables(&one.blocks, &one.rules);
|
||||
assert_eq!(found.len(), 2, "the page has two grids");
|
||||
let read = craft_rtf::doc::import(r.as_bytes()).unwrap().body.iter().filter(|b| matches!(&***b, craft_wordmodel::Block::Table(_))).count();
|
||||
assert_eq!(read, 2, "{r}");
|
||||
}
|
||||
|
||||
/// A hard line ending in the text (LF, CR or CRLF) is a line break inside its paragraph or table
|
||||
/// cell, which RTF readers keep (storytold/pdfcraft#4723, by KyleKassen): they ignore a bare line
|
||||
/// ending as whitespace.
|
||||
#[test]
|
||||
fn rtf_keeps_hard_line_breaks_in_paragraphs_and_cells() {
|
||||
let mut paragraph = page();
|
||||
paragraph.blocks.truncate(1);
|
||||
paragraph.blocks[0].text = "First\nSecond\r\nThird\rFourth".into();
|
||||
paragraph.blocks[0].italic = true;
|
||||
paragraph.images.clear();
|
||||
let r = rtf(&[paragraph]);
|
||||
let texts: Vec<String> = rtf_sections(&r).into_iter().flat_map(|s| s.1).collect();
|
||||
assert_eq!(texts, ["First\nSecond\nThird\nFourth"], "one paragraph, four lines: {r}");
|
||||
|
||||
let mut table = table_page();
|
||||
table.blocks[0].text = "Meter\nnumber".into();
|
||||
table.blocks[4].text = "kWh\r\nunit".into();
|
||||
let r = rtf(&[table]);
|
||||
let back = craft_rtf::read(r.as_bytes()).unwrap();
|
||||
let cells: Vec<String> = back
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| if let craft_rtf::Block::Table(t) = b { Some(t) } else { None })
|
||||
.flat_map(|t| t.rows.iter().flatten())
|
||||
.map(|c| c.paras.iter().map(|p| p.text()).collect())
|
||||
.collect();
|
||||
assert!(cells.contains(&"Meter\nnumber".to_string()) && cells.contains(&"kWh\nunit".to_string()), "{cells:?}");
|
||||
}
|
||||
|
||||
/// The Word export names PdfCraft as its application, its body font (Arial) in a font table that
|
||||
/// says it is a sans-serif, so a reader without it draws a like face.
|
||||
#[test]
|
||||
fn word_names_pdfcraft_and_its_fonts() {
|
||||
let zip = docx(&[page()], "Report");
|
||||
assert!(part(&zip, "docProps/app.xml").contains("<Application>PdfCraft</Application>"));
|
||||
let fonts = part(&zip, "word/fontTable.xml");
|
||||
assert!(fonts.contains(r#"<w:font w:name="Arial"><w:family w:val="swiss"/>"#), "{fonts}");
|
||||
assert_eq!(craft_docx::read(&zip).unwrap().styles.default_chr.font.as_deref(), Some("Arial"));
|
||||
}
|
||||
|
||||
/// A positioned page's text boxes have a VML fallback, which Word 2007 reads (it refuses a Word
|
||||
/// 2010 shape on its own).
|
||||
#[test]
|
||||
fn word_text_boxes_have_a_fallback_for_word_2007() {
|
||||
let mut p = table_page();
|
||||
p.blocks[0].rotation = 45.0;
|
||||
let xml = part(&docx(&[p], "Rotated"), "word/document.xml");
|
||||
let boxes = xml.matches("<wps:txbx>").count();
|
||||
assert!(boxes > 0, "{xml}");
|
||||
assert_eq!(xml.matches("<mc:Fallback>").count(), boxes, "{xml}");
|
||||
assert!(xml.contains("<v:textbox"), "{xml}");
|
||||
}
|
||||
|
||||
/// Rotated text is one text box turned with it, as wide as the text's run, not a column of
|
||||
/// letters: the W-4 draft's "DRAFT — DO NOT FILE" down its margin.
|
||||
#[test]
|
||||
fn word_rotated_text_is_a_turned_line() {
|
||||
let mut p = page();
|
||||
p.blocks.push(Block {
|
||||
text: "DRAFT — DO NOT FILE".into(),
|
||||
// Running up the left margin: 11 pt text turned a quarter, so its box is tall and narrow.
|
||||
rect: [20.0, 200.0, 31.0, 330.0],
|
||||
size: 11.0,
|
||||
bold: false,
|
||||
italic: false,
|
||||
color: [0.0; 3],
|
||||
rotation: 90.0,
|
||||
space_around: [false; 2],
|
||||
});
|
||||
let doc = craft_docx::read(&docx(&[p], "Draft")).unwrap();
|
||||
let objects = body_objects(&doc);
|
||||
let draft = objects.iter().copied().find(|o| shape_text(&doc, o) == "DRAFT — DO NOT FILE").expect("the margin text");
|
||||
let craft_wordmodel::InlineObject::Shape { w, h, float, .. } = draft else { panic!("not a shape") };
|
||||
assert!((float.rot - 270.0).abs() < 0.01, "{}", float.rot);
|
||||
assert!((*w - 130.0).abs() < 0.5 && (*h - 11.0).abs() < 0.5, "unturned, it is a line: {w} x {h}");
|
||||
}
|
||||
|
||||
/// A line break or a tab inside a block's text stays one in its Word paragraph, in a table cell
|
||||
/// too (storytold/pdfcraft#5112 by KyleKassen made Word export write them).
|
||||
#[test]
|
||||
fn word_keeps_line_breaks_and_tabs_inside_paragraphs_and_cells() {
|
||||
let mut p = page();
|
||||
p.blocks.truncate(1);
|
||||
p.blocks[0].text = "First\nSecond\r\nThird\tafter a tab".into();
|
||||
p.images.clear();
|
||||
let doc = craft_docx::read(&docx(&[p], "Breaks")).unwrap();
|
||||
let texts: Vec<String> = body_paragraphs(&doc).iter().map(|p| p.plain_text()).filter(|t| !t.is_empty()).collect();
|
||||
assert_eq!(texts, ["First\nSecond\nThird\tafter a tab"]);
|
||||
|
||||
let mut t = table_page();
|
||||
t.blocks[0].text = "Meter\nnumber".into();
|
||||
t.blocks[4].text = "kWh\tunit".into();
|
||||
let tables = docx_tables(&docx(&[t], "Breaks"));
|
||||
let cells: Vec<String> = tables
|
||||
.iter()
|
||||
.flat_map(|t| t.rows.iter().flat_map(|r| &r.cells))
|
||||
.map(|c| c.blocks.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }).collect())
|
||||
.collect();
|
||||
assert!(cells.contains(&"Meter\nnumber".to_string()) && cells.contains(&"kWh\tunit".to_string()), "{cells:?}");
|
||||
}
|
||||
@@ -7229,8 +7229,8 @@ milestone = "M10"
|
||||
status = "partial"
|
||||
commands = ["export.docx"]
|
||||
tools = ["doc_export_office"]
|
||||
evidence = ["crates/export/src/tests.rs::word_table_cell_widths_follow_the_columns_they_span", "crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/edit/src/tests.rs::reading_keeps_dotted_leader_entries_whole_and_in_order", "crates/engine/src/tests.rs::exporting_office_keeps_dotted_leader_entries_as_paragraphs", "crates/export/src/tests.rs::word_does_not_invent_borders_for_aligned_invoice_fields", "crates/export/src/tests.rs::word_overlap_does_not_consume_invoice_body_space", "crates/export/src/tests.rs::word_keeps_a_page_with_a_clear_image_and_big_title_in_flow", "crates/export/src/tests.rs::word_rotated_pages_keep_separate_page_sizes_and_unique_shapes", "crates/engine/src/tests.rs::office_export_positions_follow_the_displayed_crop_rotation_and_units", "crates/automation/tests/it/automation.rs::exporting_an_invoice_to_word_keeps_the_watermark_out_of_flow", "crates/export/src/tests.rs::docx_is_a_word_package", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/engine/src/tests.rs::exporting_office_files_keeps_text_colour", "crates/export/src/tests.rs::grid_text_becomes_a_real_table_in_every_format", "crates/export/src/tests.rs::a_link_inside_a_sentence_is_not_a_table_column", "crates/export/src/tests.rs::sentences_that_run_on_into_links_are_not_a_table", "crates/export/src/tests.rs::a_superscript_beside_a_number_keeps_its_table", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/engine/src/tests.rs::exporting_office_files_keeps_images", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::docx_keeps_a_shared_page_background", "crates/edit/src/tests.rs::a_page_painted_first_with_a_full_page_fill_has_that_background", "crates/engine/src/tests.rs::exporting_to_word_keeps_the_page_background", "crates/export/src/tests.rs::an_italic_word_stays_in_its_sentence", "crates/export/src/tests.rs::a_sentence_keeps_its_reading_order", "crates/export/src/tests.rs::runs_keep_the_spaces_the_source_had_between_them", "crates/export/src/tests.rs::a_paragraph_is_a_heading_only_when_its_text_is", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_an_italic_word_inside_its_sentence", "crates/export/src/tests.rs::word_and_html_take_the_documents_language", "crates/engine/src/tests.rs::office_exports_take_the_documents_language", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_slanted_word_that_leans_into_the_next_stays_in_its_line", "crates/export/src/tests.rs::a_paragraph_breaks_where_its_line_does_not_run_on", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_wrapped_sentence_in_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table", "crates/export/src/tests.rs::a_bullet_is_never_a_table_cell", "crates/export/src/tests.rs::a_long_bulleted_list_keeps_every_bullet_with_its_item", "crates/export/src/tests.rs::a_dash_in_a_table_row_stays_a_cell", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_bulleted_list_as_paragraphs"]
|
||||
notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Flowing Word document: paragraphs, Heading 1/2 from larger text, bold/italic, text colour (fill as sRGB; gray/CMYK converted naively, colour spaces via cs/sc read as black), detected tables with spans/empty cells (borderless, except single borders along the grid lines the page draws, #5149) (cell widths sum the grid columns they occupy, including cells after spans, verified in the XML; a row whose blocks run on into each other, such as a link or superscript inside a sentence, or overlap, as a paragraph's lines do, is text and not a table row, #2806), per-page sections/sizes, the page colour (a full-page opaque fill painted first, such as Edit a PDF ▸ Background) as the document background when every page shares one non-white colour (Word has no per-page background, so differing colours are dropped; #2992; checked in the XML only, not yet opened in Word), and positioned editable text/artwork only for pages with rotated text or text overlapped by an image or watermark-sized text, other pages flowing with inline images (#773); synthetic invoice regression; dotted-leader contents entries keep the title, dots and page number together in separate paragraphs (#1757); the emitted package validates with Open XML SDK 2.20 (Office 2010 schema). Word/LibreOffice rendering of the positioned output remains unverified. Pictures on positioned pages are DrawingML anchors behind the text (a VML rectangle with an image showed no picture, #1936; not yet opened in Word); a Word file embeds at most 1000 pictures and 512 MiB of them. The earlier flowing output was checked with macOS textutil and opened in Microsoft Word (Windows). Characters XML forbids are dropped; the page size stays within Word's 22 in. A block that continues another on its line (an italic case name, a link, a superscript) is a run in its own size, bold/italic and colour inside that paragraph, keeping the source's word space between them, rather than a paragraph of its own; a lead-in in bold no longer makes its whole line a heading (#4158); a slanted run whose box leans into the next word by up to 0.3 of its size still runs on into it. A paragraph whose last line reaches the right edge of the page's text runs on into the line just below it that starts at the same left edge in the same size, so a sentence the reading blocks split at a style change stays one paragraph across its lines; headings, list items, a line that ends a sentence, an indented line and one after paragraph space keep their break (#4158). A list whose bullets are blocks of their own (a bullet in a symbol font a tab stop before the item's text, as Word writes it, U+F0B7 and U+F0A7 included) is one paragraph per item, the bullet first, and not a borderless two-column table: a bullet is never a table cell, and a dash or middle dot counts as a bullet only when nothing starts left of it on its line. The PDF's language (`/Lang`, when it is a well formed BCP 47 tag) is the default language of the text, in the attribute Word keeps for its script (East Asian, right to left or other), so Word checks the spelling in it rather than in English (checked in the XML only, not yet opened in Word). Not yet: Word list numbering (an item is a plain paragraph that starts with its bullet), a bullet drawn in the standard Symbol font without a ToUnicode map (it never reaches export, though text extraction reads it), a paragraph whose rows the reading blocks already grouped past a style change (the exporter does not see where such a block's last row ends), a wrapped line that ends in a full stop or colon, a page whose only text is short lines that end without punctuation, such as a poem (its longest line counts as full, so the lines join), a first-line indent, lines with more than half their font size of space between them (as 1.5 or double line spacing leaves), text in columns, exact font matching, vector rules other than a table grid, arbitrary paint-order/transparency, general exact layout fidelity."
|
||||
evidence = ["crates/export/src/tests.rs::word_table_cell_widths_follow_the_columns_they_span", "crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/edit/src/tests.rs::reading_keeps_dotted_leader_entries_whole_and_in_order", "crates/engine/src/tests.rs::exporting_office_keeps_dotted_leader_entries_as_paragraphs", "crates/export/src/tests.rs::word_does_not_invent_borders_for_aligned_invoice_fields", "crates/export/src/tests.rs::word_overlap_does_not_consume_invoice_body_space", "crates/export/src/tests.rs::word_keeps_a_page_with_a_clear_image_and_big_title_in_flow", "crates/export/src/tests.rs::word_rotated_pages_keep_separate_page_sizes_and_unique_shapes", "crates/engine/src/tests.rs::office_export_positions_follow_the_displayed_crop_rotation_and_units", "crates/automation/tests/it/automation.rs::exporting_an_invoice_to_word_keeps_the_watermark_out_of_flow", "crates/export/src/tests.rs::word_names_pdfcraft_and_its_fonts", "crates/export/src/tests.rs::word_text_boxes_have_a_fallback_for_word_2007", "crates/export/src/tests.rs::word_rotated_text_is_a_turned_line", "crates/export/src/tests.rs::word_keeps_line_breaks_and_tabs_inside_paragraphs_and_cells", "crates/export/src/tests.rs::docx_is_a_word_package", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/engine/src/tests.rs::exporting_office_files_keeps_text_colour", "crates/export/src/tests.rs::grid_text_becomes_a_real_table_in_every_format", "crates/export/src/tests.rs::a_link_inside_a_sentence_is_not_a_table_column", "crates/export/src/tests.rs::sentences_that_run_on_into_links_are_not_a_table", "crates/export/src/tests.rs::a_superscript_beside_a_number_keeps_its_table", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/engine/src/tests.rs::exporting_office_files_keeps_images", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::docx_keeps_a_shared_page_background", "crates/edit/src/tests.rs::a_page_painted_first_with_a_full_page_fill_has_that_background", "crates/engine/src/tests.rs::exporting_to_word_keeps_the_page_background", "crates/export/src/tests.rs::an_italic_word_stays_in_its_sentence", "crates/export/src/tests.rs::a_sentence_keeps_its_reading_order", "crates/export/src/tests.rs::runs_keep_the_spaces_the_source_had_between_them", "crates/export/src/tests.rs::a_paragraph_is_a_heading_only_when_its_text_is", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_an_italic_word_inside_its_sentence", "crates/export/src/tests.rs::word_and_html_take_the_documents_language", "crates/engine/src/tests.rs::office_exports_take_the_documents_language", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_slanted_word_that_leans_into_the_next_stays_in_its_line", "crates/export/src/tests.rs::a_paragraph_breaks_where_its_line_does_not_run_on", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_wrapped_sentence_in_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table", "crates/export/src/tests.rs::a_bullet_is_never_a_table_cell", "crates/export/src/tests.rs::a_long_bulleted_list_keeps_every_bullet_with_its_item", "crates/export/src/tests.rs::a_dash_in_a_table_row_stays_a_cell", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_bulleted_list_as_paragraphs"]
|
||||
notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Flowing Word document: paragraphs, Heading 1/2 from larger text, bold/italic, text colour (fill as sRGB; gray/CMYK converted naively, colour spaces via cs/sc read as black), detected tables with spans/empty cells (borderless, except single borders along the grid lines the page draws, #5149) (cell widths sum the grid columns they occupy, including cells after spans, verified in the XML; a row whose blocks run on into each other, such as a link or superscript inside a sentence, or overlap, as a paragraph's lines do, is text and not a table row, #2806), per-page sections/sizes, the page colour (a full-page opaque fill painted first, such as Edit a PDF ▸ Background) as the document background when every page shares one non-white colour (Word has no per-page background, so differing colours are dropped; #2992; checked in the XML only, not yet opened in Word), and positioned editable text/artwork only for pages with rotated text or text overlapped by an image or watermark-sized text, other pages flowing with inline images (#773); synthetic invoice regression; dotted-leader contents entries keep the title, dots and page number together in separate paragraphs (#1757); the emitted package validates with Open XML SDK 2.20 (Office 2010 schema). Written by craft-docx from the word model PdfCraft's RTF export also uses (storytold/craft-libs#793): every text box has a VML fallback, so Word 2007 opens positioned pages; rotated text is a turned text box, drawn as a line (the W-4 draft's margin text was a column of letters); pictures on positioned pages float behind the text, over watermark-sized text; the body font is Arial, with a font table saying it is a sans; docProps/app.xml names PdfCraft; a picture drawn many times is stored once. Seven public PDFs (IRS W-9, 1040 and W-4 drafts, arXiv 1706.03762, NIST CSF 2.0, a W3C table, the BLS Employment Situation) open in Word 16, Word 2007 and LibreOffice with the same words as before; flowing pages run a little longer in Arial than in the Times New Roman Word fell back to. A Word file embeds at most 1000 pictures and 512 MiB of them. The earlier flowing output was checked with macOS textutil and opened in Microsoft Word (Windows). Characters XML forbids are dropped; the page size stays within Word's 22 in. A block that continues another on its line (an italic case name, a link, a superscript) is a run in its own size, bold/italic and colour inside that paragraph, keeping the source's word space between them, rather than a paragraph of its own; a lead-in in bold no longer makes its whole line a heading (#4158); a slanted run whose box leans into the next word by up to 0.3 of its size still runs on into it. A paragraph whose last line reaches the right edge of the page's text runs on into the line just below it that starts at the same left edge in the same size, so a sentence the reading blocks split at a style change stays one paragraph across its lines; headings, list items, a line that ends a sentence, an indented line and one after paragraph space keep their break (#4158). A list whose bullets are blocks of their own (a bullet in a symbol font a tab stop before the item's text, as Word writes it, U+F0B7 and U+F0A7 included) is one paragraph per item, the bullet first, and not a borderless two-column table: a bullet is never a table cell, and a dash or middle dot counts as a bullet only when nothing starts left of it on its line. The PDF's language (`/Lang`, when it is a well formed BCP 47 tag) is the default language of the text, in the attribute Word keeps for its script (East Asian, right to left or other), so Word checks the spelling in it rather than in English (checked in the XML only, not yet opened in Word). Not yet: Word list numbering (an item is a plain paragraph that starts with its bullet), a bullet drawn in the standard Symbol font without a ToUnicode map (it never reaches export, though text extraction reads it), a paragraph whose rows the reading blocks already grouped past a style change (the exporter does not see where such a block's last row ends), a wrapped line that ends in a full stop or colon, a page whose only text is short lines that end without punctuation, such as a poem (its longest line counts as full, so the lines join), a first-line indent, lines with more than half their font size of space between them (as 1.5 or double line spacing leaves), text in columns, exact font matching, vector rules other than a table grid, arbitrary paint-order/transparency, general exact layout fidelity."
|
||||
|
||||
[[feature]]
|
||||
id = "create.export-rtf"
|
||||
@@ -7241,8 +7241,8 @@ milestone = "M10"
|
||||
status = "shipped"
|
||||
commands = ["export.rtf"]
|
||||
tools = ["doc_export_office"]
|
||||
evidence = ["crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/export/src/tests.rs::rtf_escapes_and_sizes", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table"]
|
||||
notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Paragraphs with sizes, bold, italic, text colour (colortbl), Unicode; a block that continues another on its line is a formatted group inside that paragraph (#4158), and a paragraph that wraps onto the next line after a style change runs on there, with the same rules and limits as Word export; a list whose bullets are blocks of their own is a paragraph per item, not a table, as in Word export; page breaks. Images are left out."
|
||||
evidence = ["crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/export/src/tests.rs::rtf_escapes_and_sizes", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table", "crates/export/src/tests.rs::rtf_keeps_pictures", "crates/export/src/tests.rs::rtf_keeps_pages_without_text", "crates/export/src/tests.rs::rtf_headings_have_heading_styles", "crates/export/src/tests.rs::rtf_keeps_hard_line_breaks_in_paragraphs_and_cells"]
|
||||
notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Paragraphs with sizes, bold, italic, text colour (colortbl), Unicode; a block that continues another on its line is a formatted group inside that paragraph (#4158), and a paragraph that wraps onto the next line after a style change runs on there, with the same rules and limits as Word export; a list whose bullets are blocks of their own is a paragraph per item, not a table, as in Word export; written by craft-rtf's full writer from the word model: each page a section of its own size (blank pages kept), pictures inline, Heading 1 and 2 styles, tables that touch kept apart, hard line breaks kept inside their paragraph or cell, and the title. Not kept: the PDF's language (the writer names English), and positioned pages flow."
|
||||
|
||||
|
||||
[[feature]]
|
||||
|
||||
Reference in new issue
Block a user