mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-20 19:18:41 +00:00
* export, xfdf: cut over portable HTML writer and XFDF/FDF grammar to craft-libs (#778) * fix(xfdf): align craft-xml rev with craft-xfdf and deref standalone El * fix(xfdf): remove redundant deref on standalone(el, ns) * xfdf, export: update craft-libs pin and add XFDF annotation round-trip test * chore: align craft-xml rev with craft-xfdf * chore: repin craft-xml to craft-libs main * chore: repin craft-xml, craft-xfdf, craft-html to craft-libs main * test(xfdf): pass &str to import_comments in round-trip test * test(xfdf): bind dst.get(dst_ref) before as_dict * test(fonts): import pdfcraft_cos::Stream in embedding tests * test(xfdf): update newly added square annotation instead of widget[0] * test(xfdf): read newly imported annotation at Annots.last() in roundtrip test
This commit is contained in:
1 parent
6de83353bd
commit
e1d2f32e58
12 files changed
+114
-544
No files matched your search
Generated
+57
-30
@@ -966,6 +966,17 @@ dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chardetng"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"encoding_rs",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
@@ -1213,6 +1224,11 @@ dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
@@ -1298,6 +1314,14 @@ name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0"
|
||||
dependencies = [
|
||||
"craft-mime 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
@@ -1380,7 +1404,7 @@ version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33"
|
||||
dependencies = [
|
||||
"craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
"craft-html",
|
||||
"craft-html 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)",
|
||||
]
|
||||
|
||||
@@ -1434,13 +1458,24 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
@@ -1588,7 +1623,7 @@ name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"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)",
|
||||
@@ -1731,9 +1766,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xfdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72#e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -1747,6 +1782,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1767,25 +1812,6 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72#e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -5059,12 +5085,13 @@ name = "pdfcraft-export"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"craft-docx",
|
||||
"craft-html 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"craft-markdown",
|
||||
"craft-mime",
|
||||
"craft-mime 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
|
||||
"craft-pptx",
|
||||
"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-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -5217,7 +5244,7 @@ name = "pdfcraft-preflight"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8503f24cb845268f47f97e829491114fe9ad1bfa)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"flate2",
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
@@ -5245,7 +5272,7 @@ name = "pdfcraft-redact"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"pdfcraft-annot",
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
@@ -5414,7 +5441,7 @@ dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-image-codecs",
|
||||
"craft-xfa",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-fonts",
|
||||
"sha2 0.11.1",
|
||||
@@ -5428,7 +5455,7 @@ dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-csv",
|
||||
"craft-xfdf",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)",
|
||||
"pdfcraft-annot",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-forms",
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0"
|
||||
# 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 = "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-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "1546550b0d4b79b8156a1fefaac8b3b317a4aee0" }
|
||||
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" }
|
||||
|
||||
@@ -16,6 +16,7 @@ craft-mime.workspace = true
|
||||
craft-rtf = { workspace = true, features = ["doc"] }
|
||||
craft-wordmodel.workspace = true
|
||||
craft-docx.workspace = true
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "1546550b0d4b79b8156a1fefaac8b3b317a4aee0", version = "0.1.0", features = ["standalone"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
craft-pptx.workspace = true
|
||||
craft-xml.workspace = true
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::as_docx::{rgb8, room_for};
|
||||
use super::html::{self, HtmlBlock, HtmlCell, HtmlRun, HtmlTable};
|
||||
use super::layout::{Image, Item, Page, items};
|
||||
#[cfg(test)]
|
||||
use super::layout::{Run, Table};
|
||||
use craft_html::standalone::{self as html, HtmlBlock, HtmlCell, HtmlRun, HtmlTable};
|
||||
|
||||
pub(crate) use super::html::allowed;
|
||||
pub(crate) use craft_html::standalone::allowed;
|
||||
|
||||
/// The longest language tag the exports write. BCP 47 sets no maximum (35 characters is only
|
||||
/// the least a protocol must hold), so this bounds only what a PDF's `/Lang` can put in a file.
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
//! Portable standalone HTML document writer (no PDF layout, reading order, or export policy).
|
||||
|
||||
pub(crate) use craft_mime::transfer::base64;
|
||||
|
||||
/// Whether a character may appear in the output. XML 1.0 forbids the C0 controls other than tab,
|
||||
/// line feed and carriage return, and U+FFFE/U+FFFF.
|
||||
pub(crate) fn allowed(c: char) -> bool {
|
||||
matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}')
|
||||
}
|
||||
|
||||
pub(crate) fn esc(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
for c in s.chars().filter(|c| allowed(*c)) {
|
||||
match c {
|
||||
'&' => o.push_str("&"),
|
||||
'<' => o.push_str("<"),
|
||||
'>' => o.push_str(">"),
|
||||
'"' => o.push_str("""),
|
||||
c => o.push(c),
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// An inline run of text for portable HTML rendering.
|
||||
pub(crate) struct HtmlRun<'a> {
|
||||
pub text: &'a str,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub color: [u8; 3],
|
||||
}
|
||||
|
||||
/// A single table cell for portable HTML rendering.
|
||||
pub(crate) struct HtmlCell<'a> {
|
||||
pub text: &'a str,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub color: [u8; 3],
|
||||
pub span: usize,
|
||||
}
|
||||
|
||||
/// A table of rows of cells for portable HTML rendering.
|
||||
pub(crate) struct HtmlTable<'a> {
|
||||
pub rows: Vec<Vec<HtmlCell<'a>>>,
|
||||
}
|
||||
|
||||
/// A block-level element in a portable HTML document.
|
||||
pub(crate) enum HtmlBlock<'a> {
|
||||
Para { runs: Vec<HtmlRun<'a>>, level: u8 },
|
||||
Table(HtmlTable<'a>),
|
||||
Image { mime: &'a str, bytes: &'a [u8] },
|
||||
PageBreak,
|
||||
}
|
||||
|
||||
fn rgb_hex(rgb: [u8; 3]) -> Option<String> {
|
||||
let [r, g, b] = rgb;
|
||||
(r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}"))
|
||||
}
|
||||
|
||||
fn style_color(rgb: [u8; 3], simple: bool) -> String {
|
||||
if simple { String::new() } else { rgb_hex(rgb).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) }
|
||||
}
|
||||
|
||||
pub(crate) fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String {
|
||||
if text.trim().is_empty() {
|
||||
return text;
|
||||
}
|
||||
if italic {
|
||||
text = format!("<em>{text}</em>");
|
||||
}
|
||||
if bold {
|
||||
text = format!("<strong>{text}</strong>");
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
pub(crate) fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option<String> {
|
||||
let non_empty: Vec<_> = runs.iter().map(|r| (r, esc(r.text))).filter(|(_, text)| !text.is_empty()).collect();
|
||||
let &(first, _) = non_empty.iter().find(|(_, text)| !text.trim().is_empty())?;
|
||||
let mut t = String::new();
|
||||
for (run, text) in non_empty {
|
||||
if text.trim().is_empty() {
|
||||
t.push_str(&text);
|
||||
continue;
|
||||
}
|
||||
let mut out = wrap_inline(text, run.bold && lvl == 0, run.italic);
|
||||
// The paragraph has its first visible run's colour; a run in another colour says so.
|
||||
if !simple && run.color != first.color {
|
||||
let [red, green, blue] = run.color;
|
||||
out = format!("<span style=\"color:#{red:02X}{green:02X}{blue:02X}\">{out}</span>");
|
||||
}
|
||||
t.push_str(&out);
|
||||
}
|
||||
let style = style_color(first.color, simple);
|
||||
Some(match lvl.min(6) {
|
||||
0 => format!("<p{style}>{t}</p>\n"),
|
||||
l => format!("<h{l}{style}>{t}</h{l}>\n"),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn render_table(t: &HtmlTable<'_>, simple: bool) -> String {
|
||||
let mut s = String::from("<table>\n");
|
||||
for row in &t.rows {
|
||||
s.push_str("<tr>");
|
||||
for c in row {
|
||||
let body = wrap_inline(esc(c.text), c.bold, c.italic);
|
||||
let span = if c.span > 1 { format!(" colspan=\"{}\"", c.span) } else { String::new() };
|
||||
let style = style_color(c.color, simple);
|
||||
s.push_str(&format!("<td{span}{style}>{body}</td>"));
|
||||
}
|
||||
s.push_str("</tr>\n");
|
||||
}
|
||||
s.push_str("</table>\n");
|
||||
s
|
||||
}
|
||||
|
||||
/// Render a sequence of portable HTML blocks into a standalone HTML5 document.
|
||||
pub(crate) fn render(blocks: &[HtmlBlock<'_>], title: &str, simple: bool, language: Option<&str>) -> String {
|
||||
let lang = language.map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default();
|
||||
let mut s = format!(
|
||||
"<!DOCTYPE html>\n<html{lang}>\n<head>\n<meta charset=\"utf-8\">\n<title>{}</title>\n{}\n</head>\n<body>\n",
|
||||
esc(title),
|
||||
if simple {
|
||||
""
|
||||
} else {
|
||||
"<style>body{max-width:46em;margin:2em auto;font-family:sans-serif;line-height:1.45}img{max-width:100%}hr{border:0;border-top:1px solid #ccc;margin:2em 0}table{border-collapse:collapse;margin:1em 0}td,th{border:1px solid #999;padding:2px 6px;vertical-align:top}</style>"
|
||||
}
|
||||
);
|
||||
for block in blocks {
|
||||
match block {
|
||||
HtmlBlock::Para { runs, level } => {
|
||||
if let Some(p) = render_para(runs, *level, simple) {
|
||||
s.push_str(&p);
|
||||
}
|
||||
}
|
||||
HtmlBlock::Table(t) => s.push_str(&render_table(t, simple)),
|
||||
HtmlBlock::Image { mime, bytes } => {
|
||||
s.push_str(&format!("<p><img alt=\"\" src=\"data:{mime};base64,{}\"></p>\n", base64(bytes)));
|
||||
}
|
||||
HtmlBlock::PageBreak => s.push_str("<hr>\n"),
|
||||
}
|
||||
}
|
||||
s.push_str("</body>\n</html>\n");
|
||||
s
|
||||
}
|
||||
@@ -23,7 +23,6 @@ mod as_rtf;
|
||||
mod as_word;
|
||||
mod clip;
|
||||
mod flow;
|
||||
mod html;
|
||||
mod layout;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -36,11 +35,11 @@ pub use as_markdown::markdown;
|
||||
use as_markdown::{emphasis, paragraph};
|
||||
pub use as_rtf::{rtf, rtf_with_title, rtf_with_title_checked};
|
||||
pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family};
|
||||
pub(crate) use craft_html::standalone::esc;
|
||||
#[cfg(test)]
|
||||
use craft_html::standalone::{allowed, base64};
|
||||
#[cfg(test)]
|
||||
use flow::list_item;
|
||||
pub(crate) use html::esc;
|
||||
#[cfg(test)]
|
||||
use html::{allowed, base64};
|
||||
pub use layout::{Block, Cell, Image, Page, Table};
|
||||
#[cfg(test)]
|
||||
use layout::{LOOKUP_STEPS, MAX_COLS, body_size};
|
||||
|
||||
@@ -9,7 +9,7 @@ license.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-xfdf = { git = "https://github.com/storytold/craft-libs", rev = "e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72", version = "0.1.0" }
|
||||
craft-xfdf = { git = "https://github.com/storytold/craft-libs", rev = "1546550b0d4b79b8156a1fefaac8b3b317a4aee0", version = "0.1.0" }
|
||||
pdfcraft-cos = { workspace = true }
|
||||
pdfcraft-annot = { workspace = true }
|
||||
pdfcraft-forms = { workspace = true }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::common::{MAX_DEPTH, rect_strict, text_of};
|
||||
use super::grammar::fdf_annot_skip_key;
|
||||
use super::xfdf::{add_popup, apply_values, find_by_name, place};
|
||||
use super::*;
|
||||
use craft_xfdf::grammar::fdf_annot_skip_key;
|
||||
|
||||
fn pdf_string(s: &str) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
//! Portable XFDF annotation and FDF grammar (no PDF COS document or annotation models).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use super::common::{check_form_xml_depth, csv, el_text, esc, hex, n, parse_form_xml, xml_nesting_depth};
|
||||
|
||||
/// XFDF's own namespace (ISO 19444-1).
|
||||
pub(crate) const XFDF_NS: &str = "http://ns.adobe.com/xfdf/";
|
||||
|
||||
/// Rich text deeper than this is written as text rather than as markup, so the XFDF it goes into
|
||||
/// stays well inside the nesting the reader accepts (`MAX_XML_DEPTH`).
|
||||
const MAX_RICH_DEPTH: usize = 512;
|
||||
|
||||
pub(crate) const SUBTYPES: [(&str, &str); 17] = [
|
||||
("Text", "text"),
|
||||
("FreeText", "freetext"),
|
||||
("Line", "line"),
|
||||
("Square", "square"),
|
||||
("Circle", "circle"),
|
||||
("Polygon", "polygon"),
|
||||
("PolyLine", "polyline"),
|
||||
("Highlight", "highlight"),
|
||||
("Underline", "underline"),
|
||||
("Squiggly", "squiggly"),
|
||||
("StrikeOut", "strikeout"),
|
||||
("Stamp", "stamp"),
|
||||
("Caret", "caret"),
|
||||
("Ink", "ink"),
|
||||
("FileAttachment", "fileattachment"),
|
||||
("Sound", "sound"),
|
||||
("Redact", "redact"),
|
||||
];
|
||||
|
||||
pub(crate) const FLAGS: [(i64, &str); 9] = [
|
||||
(1, "invisible"),
|
||||
(2, "hidden"),
|
||||
(4, "print"),
|
||||
(8, "nozoom"),
|
||||
(16, "norotate"),
|
||||
(32, "noview"),
|
||||
(64, "readonly"),
|
||||
(128, "locked"),
|
||||
(256, "togglenoview"),
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum BorderStyle {
|
||||
Solid,
|
||||
Dash,
|
||||
Bevelled,
|
||||
Inset,
|
||||
Underline,
|
||||
}
|
||||
|
||||
impl BorderStyle {
|
||||
pub(crate) fn as_pdf_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Solid => "S",
|
||||
Self::Dash => "D",
|
||||
Self::Bevelled => "B",
|
||||
Self::Inset => "I",
|
||||
Self::Underline => "U",
|
||||
}
|
||||
}
|
||||
|
||||
fn as_xfdf_attr(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Dash => Some("dash"),
|
||||
Self::Bevelled => Some("bevelled"),
|
||||
Self::Inset => Some("inset"),
|
||||
Self::Underline => Some("underline"),
|
||||
Self::Solid => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CaretSymbol {
|
||||
Paragraph,
|
||||
None,
|
||||
}
|
||||
|
||||
impl CaretSymbol {
|
||||
pub(crate) fn as_pdf_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Paragraph => "P",
|
||||
Self::None => "None",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Portable XFDF 3.0 annotation formatting attributes.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AnnotFormat {
|
||||
pub width: Option<f64>,
|
||||
pub border_style: Option<BorderStyle>,
|
||||
pub dashes: Option<Vec<f64>>,
|
||||
pub cloudy_intensity: Option<Option<f64>>,
|
||||
pub rotation: Option<i64>,
|
||||
pub justification: Option<i64>,
|
||||
pub fringe: Option<[f64; 4]>,
|
||||
pub leader_length: Option<f64>,
|
||||
pub leader_extend: Option<f64>,
|
||||
pub leader_offset: Option<f64>,
|
||||
pub caption: Option<bool>,
|
||||
pub caption_style: Option<String>,
|
||||
pub caption_offset: Option<[f64; 2]>,
|
||||
pub symbol: Option<CaretSymbol>,
|
||||
pub overlay_text: Option<String>,
|
||||
pub overlay_text_repeat: Option<bool>,
|
||||
}
|
||||
|
||||
/// Format XFDF 3.0 annotation formatting attributes into `attrs`.
|
||||
pub(crate) fn write_format_attrs(fmt: &AnnotFormat, is_free_text: bool, attrs: &mut String) {
|
||||
let list = |v: &[f64]| v.iter().map(|x| n(*x)).collect::<Vec<_>>().join(",");
|
||||
if let Some(w) = fmt.width.filter(|w| w.is_finite()) {
|
||||
let _ = write!(attrs, " width=\"{}\"", n(w));
|
||||
}
|
||||
if let Some(intensity) = fmt.cloudy_intensity {
|
||||
attrs.push_str(" style=\"cloudy\"");
|
||||
if let Some(i) = intensity.filter(|i| i.is_finite()) {
|
||||
let _ = write!(attrs, " intensity=\"{}\"", n(i));
|
||||
}
|
||||
} else if let Some(s) = fmt.border_style.and_then(BorderStyle::as_xfdf_attr) {
|
||||
let _ = write!(attrs, " style=\"{s}\"");
|
||||
}
|
||||
if let Some(dashes) = &fmt.dashes
|
||||
&& !dashes.is_empty()
|
||||
&& dashes.iter().all(|v| v.is_finite())
|
||||
{
|
||||
let _ = write!(attrs, " dashes=\"{}\"", list(dashes));
|
||||
}
|
||||
if let Some(r) = fmt.rotation {
|
||||
let _ = write!(attrs, " rotation=\"{r}\"");
|
||||
}
|
||||
if let Some(q) = fmt.justification {
|
||||
match (is_free_text, q) {
|
||||
(true, 0) => attrs.push_str(" justification=\"left\""),
|
||||
(true, 1) => attrs.push_str(" justification=\"centered\""),
|
||||
(true, 2) => attrs.push_str(" justification=\"right\""),
|
||||
(true, _) => {}
|
||||
(false, q) => {
|
||||
let _ = write!(attrs, " justification=\"{q}\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(rd) = fmt.fringe
|
||||
&& rd.iter().all(|v| v.is_finite())
|
||||
{
|
||||
let _ = write!(attrs, " fringe=\"{}\"", list(&rd));
|
||||
}
|
||||
if let Some(ll) = fmt.leader_length.filter(|v| v.is_finite()) {
|
||||
let _ = write!(attrs, " leaderLength=\"{}\"", n(ll));
|
||||
}
|
||||
if let Some(lle) = fmt.leader_extend.filter(|v| v.is_finite()) {
|
||||
let _ = write!(attrs, " leaderExtend=\"{}\"", n(lle));
|
||||
}
|
||||
if let Some(llo) = fmt.leader_offset.filter(|v| v.is_finite()) {
|
||||
let _ = write!(attrs, " leader-offset=\"{}\"", n(llo));
|
||||
}
|
||||
if let Some(cap) = fmt.caption {
|
||||
let _ = write!(attrs, " caption=\"{}\"", if cap { "yes" } else { "no" });
|
||||
}
|
||||
if let Some(cp) = &fmt.caption_style {
|
||||
let _ = write!(attrs, " caption-style=\"{}\"", esc(cp));
|
||||
}
|
||||
if let Some([h, v]) = fmt.caption_offset
|
||||
&& h.is_finite()
|
||||
&& v.is_finite()
|
||||
{
|
||||
let _ = write!(attrs, " caption-offset-h=\"{}\" caption-offset-v=\"{}\"", n(h), n(v));
|
||||
}
|
||||
match fmt.symbol {
|
||||
Some(CaretSymbol::Paragraph) => attrs.push_str(" symbol=\"paragraph\""),
|
||||
Some(CaretSymbol::None) => attrs.push_str(" symbol=\"none\""),
|
||||
None => {}
|
||||
}
|
||||
if let Some(t) = &fmt.overlay_text {
|
||||
let _ = write!(attrs, " overlay-text=\"{}\"", esc(t));
|
||||
}
|
||||
if let Some(repeat) = fmt.overlay_text_repeat {
|
||||
let _ = write!(attrs, " overlay-text-repeat=\"{repeat}\"");
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse XFDF 3.0 annotation formatting attributes from an XML element.
|
||||
pub(crate) fn parse_format_attrs(node: &craft_xml::El) -> AnnotFormat {
|
||||
let num = |a: &str| node.attr(a).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite());
|
||||
let style = node.attr("style").map(str::trim);
|
||||
let dashes = node.attr("dashes").map(csv).filter(|v| !v.is_empty() && v.iter().all(|x| *x >= 0.0) && v.iter().any(|x| *x > 0.0));
|
||||
let border_style = match style {
|
||||
Some("dash") => Some(BorderStyle::Dash),
|
||||
Some("bevelled" | "beveled") => Some(BorderStyle::Bevelled),
|
||||
Some("inset") => Some(BorderStyle::Inset),
|
||||
Some("underline") => Some(BorderStyle::Underline),
|
||||
Some("solid") => Some(BorderStyle::Solid),
|
||||
_ => None,
|
||||
};
|
||||
let cloudy_intensity = (style == Some("cloudy")).then(|| Some(num("intensity").unwrap_or(1.0).clamp(0.0, 2.0)));
|
||||
let (h, v) = (num("caption-offset-h"), num("caption-offset-v"));
|
||||
AnnotFormat {
|
||||
width: num("width"),
|
||||
border_style,
|
||||
dashes,
|
||||
cloudy_intensity,
|
||||
rotation: node.attr("rotation").and_then(|r| r.trim().parse::<i32>().ok()).map(i64::from),
|
||||
justification: match node.attr("justification").map(str::trim) {
|
||||
Some("left" | "0") => Some(0),
|
||||
Some("centered" | "center" | "1") => Some(1),
|
||||
Some("right" | "2") => Some(2),
|
||||
_ => None,
|
||||
},
|
||||
fringe: node.attr("fringe").map(csv).and_then(|r| r.try_into().ok()),
|
||||
leader_length: num("leaderLength"),
|
||||
leader_extend: num("leaderExtend").filter(|v| *v >= 0.0),
|
||||
leader_offset: num("leader-offset").filter(|v| *v >= 0.0),
|
||||
caption: match node.attr("caption").map(str::trim) {
|
||||
Some("yes" | "true") => Some(true),
|
||||
Some("no" | "false") => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
caption_style: node.attr("caption-style").map(str::trim).filter(|c| matches!(*c, "Inline" | "Top")).map(str::to_owned),
|
||||
caption_offset: (h.is_some() || v.is_some()).then(|| [h.unwrap_or(0.0), v.unwrap_or(0.0)]),
|
||||
symbol: match node.attr("symbol").map(str::trim) {
|
||||
Some("paragraph" | "P") => Some(CaretSymbol::Paragraph),
|
||||
Some("none" | "None") => Some(CaretSymbol::None),
|
||||
_ => None,
|
||||
},
|
||||
overlay_text: node.attr("overlay-text").map(str::to_owned),
|
||||
overlay_text_repeat: match node.attr("overlay-text-repeat").map(str::trim) {
|
||||
Some("true" | "yes") => Some(true),
|
||||
Some("false" | "no") => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn format_flags(flags: i64) -> String {
|
||||
FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
pub(crate) fn parse_flags(attr: Option<&str>) -> i64 {
|
||||
attr.unwrap_or("print")
|
||||
.split(',')
|
||||
.filter_map(|f| FLAGS.iter().find(|(_, s)| s.eq_ignore_ascii_case(f.trim())).map(|x| x.0))
|
||||
.fold(0, |bits, flag| bits | flag)
|
||||
}
|
||||
|
||||
/// Pairs `x,y;x,y;…` (XFDF vertices and ink gestures).
|
||||
pub(crate) fn pairs(text: &str) -> Vec<[f64; 2]> {
|
||||
text.split(';').filter_map(|p| if let [x, y] = csv(p).as_slice() { Some([*x, *y]) } else { None }).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn format_pairs(pts: &[[f64; 2]]) -> String {
|
||||
pts.iter().map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect::<Vec<_>>().join(";")
|
||||
}
|
||||
|
||||
/// Rich text (`/RC`) as `<contents-richtext>` holds it: its root element alone (no XML
|
||||
/// declaration), when the text is well-formed XML; `None` otherwise.
|
||||
pub(crate) fn rich_text_element(rc: &str) -> Option<String> {
|
||||
let t = rc.trim_start_matches('\u{feff}');
|
||||
if xml_nesting_depth(t) > MAX_RICH_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let parsed = parse_form_xml(t).ok()?;
|
||||
Some(parsed.to_xml())
|
||||
}
|
||||
|
||||
/// A `<contents-richtext>` element's plain text, a line per paragraph: what `/Contents` gets
|
||||
/// when the element comes without `<contents>`.
|
||||
pub(crate) fn rich_plain(node: &craft_xml::El) -> String {
|
||||
fn walk(node: &craft_xml::El, out: &mut String) {
|
||||
for n in &node.children {
|
||||
match n {
|
||||
craft_xml::Node::El(el) => {
|
||||
if el.local() == "br" || (matches!(el.local(), "p" | "div" | "li") && !out.is_empty() && !out.ends_with('\r')) {
|
||||
out.push('\r');
|
||||
}
|
||||
walk(el, out);
|
||||
}
|
||||
craft_xml::Node::Text(t) if !(t.trim().is_empty() && t.contains('\n')) => {
|
||||
out.push_str(&t.replace("\r\n", "\r").replace('\n', "\r"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
walk(node, &mut out);
|
||||
out.trim_end_matches('\r').to_string()
|
||||
}
|
||||
|
||||
/// The one element `markup` (cut out of `rich`, a `<contents-richtext>`) as an XML
|
||||
/// document of its own: the namespaces it inherits from the XFDF around it are declared on it.
|
||||
pub(crate) fn standalone(el: &craft_xml::El, ns: &[(String, String)]) -> String {
|
||||
let mut clone = (*el).clone();
|
||||
let markup = clone.to_xml();
|
||||
if let Some((_, uri)) = ns.iter().rfind(|(p, _)| p.is_empty())
|
||||
&& !uri.is_empty()
|
||||
&& uri != XFDF_NS
|
||||
&& !clone.has_attr("xmlns")
|
||||
{
|
||||
clone.set_attr("xmlns", uri);
|
||||
}
|
||||
for (prefix, uri) in ns {
|
||||
if prefix.is_empty() || prefix == "xml" {
|
||||
continue;
|
||||
}
|
||||
let attr_name = format!("xmlns:{prefix}");
|
||||
if markup.contains(&format!("{prefix}:")) && !clone.has_attr(&attr_name) {
|
||||
clone.set_attr(&attr_name, uri);
|
||||
}
|
||||
}
|
||||
clone.to_xml()
|
||||
}
|
||||
|
||||
/// Whether `text` is XFDF with comments in it (what a paste of copied comments carries).
|
||||
pub fn is_xfdf_comments(text: &str) -> bool {
|
||||
let head: String = text.chars().take(400).collect();
|
||||
head.contains("<xfdf") && text.contains("<annots")
|
||||
}
|
||||
|
||||
/// Every comment element of an XFDF text, in order (none when it is no XFDF).
|
||||
pub(crate) fn with_comment_nodes(text: &str, mut f: impl FnMut(&craft_xml::El)) {
|
||||
if check_form_xml_depth(text).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(root) = parse_form_xml(text) else { return };
|
||||
if root.local() != "xfdf" {
|
||||
return;
|
||||
}
|
||||
let Some(annots) = root.child(craft_xml::Local("annots")) else { return };
|
||||
for node in annots.elements() {
|
||||
if SUBTYPES.iter().any(|(_, t)| *t == node.local().to_ascii_lowercase()) {
|
||||
f(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an annotation dictionary key is skipped when exporting into FDF (ISO 32000-2 §12.7.8.3.4).
|
||||
pub(crate) fn fdf_annot_skip_key(key: &[u8], is_stamp: bool) -> bool {
|
||||
matches!(key, b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key == b"AP" && !is_stamp)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn format_color_attr(name: &str, color: &[f64], out: &mut String) {
|
||||
if let Some(c) = hex(color) {
|
||||
let _ = write!(out, " {name}=\"{c}\"");
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn rich_text_plain(node: &craft_xml::El) -> String {
|
||||
el_text(node)
|
||||
}
|
||||
@@ -23,18 +23,17 @@ use pdfcraft_forms::{FieldKind, FieldValue};
|
||||
mod appearance;
|
||||
mod common;
|
||||
mod fdf;
|
||||
mod grammar;
|
||||
mod xfdf;
|
||||
|
||||
#[cfg(test)]
|
||||
use common::{MAX_DEPTH, MAX_XML_DEPTH, arr, nums_of, parse_hex, text_of, xml_nesting_depth};
|
||||
use common::{check_form_xml_depth, el_text, esc, parse_form_xml, xml_name};
|
||||
use craft_xfdf::grammar::SUBTYPES;
|
||||
pub use craft_xfdf::grammar::is_xfdf_comments;
|
||||
pub use fdf::export_fdf;
|
||||
use fdf::{ImportBudget, fdf_body, import_fdf, walk_fdf};
|
||||
#[cfg(test)]
|
||||
use fdf::{MAX_FDF_BYTES, MAX_FDF_OBJECTS};
|
||||
use grammar::SUBTYPES;
|
||||
pub use grammar::is_xfdf_comments;
|
||||
#[cfg(test)]
|
||||
use xfdf::{LOCKED, find_by_name};
|
||||
pub use xfdf::{Outline, comment_count, comment_outlines, comments_bounds, export_xfdf, export_xfdf_comments, import_comments};
|
||||
|
||||
@@ -2789,3 +2789,47 @@ fn shared_xfdf_fields_match_retained_reader() -> Result<(), Box<dyn std::error::
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xfdf_annotation_formatting_round_trips_via_shared_grammar() {
|
||||
let mut src = blank();
|
||||
let shape = Shape::Rectangle { rect: [24.0, 48.0, 144.0, 108.0] };
|
||||
add_annotation(
|
||||
&mut src,
|
||||
&NewAnnotation { page: 0, style: Style::default_for(&shape), shape, contents: "Dashed box".into(), author: "Ada".into() },
|
||||
&Meta { id: "fmt-rt-1".into(), date: Some("D:20261119120000Z".into()) },
|
||||
)
|
||||
.unwrap();
|
||||
let page = pdfcraft_model::pages(&src)[0].obj;
|
||||
let annot_ref =
|
||||
src.get(page).as_dict().unwrap().get(b"Annots").map(|a| src.resolve(a)).unwrap().as_array().unwrap().last().unwrap().as_ref().unwrap();
|
||||
let mut bs = Dict::new();
|
||||
bs.set(b"W".to_vec(), Object::Real(2.5));
|
||||
bs.set(b"S".to_vec(), Object::name("D"));
|
||||
bs.set(b"D".to_vec(), Object::Array(vec![Object::Real(4.0), Object::Real(2.0)]));
|
||||
src.update_dict(annot_ref, |d| {
|
||||
d.set(b"BS".to_vec(), Object::Dict(bs));
|
||||
d.set(b"F".to_vec(), Object::Int(4 | 128));
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let xfdf = export_xfdf(&src, true, false, "fmt.pdf");
|
||||
assert!(is_xfdf_comments(&xfdf), "{xfdf}");
|
||||
assert!(xfdf.contains("style=\"dash\""), "{xfdf}");
|
||||
assert!(xfdf.contains("dashes=\"4,2\""), "{xfdf}");
|
||||
assert!(xfdf.contains("flags=\"print,locked\""), "{xfdf}");
|
||||
|
||||
let mut dst = blank();
|
||||
let report = import_comments(&mut dst, &xfdf, None, None, None).unwrap();
|
||||
assert_eq!(report.comments, 1, "{report:?}");
|
||||
let dst_page = pdfcraft_model::pages(&dst)[0].obj;
|
||||
let dst_ref =
|
||||
dst.get(dst_page).as_dict().unwrap().get(b"Annots").map(|a| dst.resolve(a)).unwrap().as_array().unwrap().last().unwrap().as_ref().unwrap();
|
||||
let dst_obj = dst.get(dst_ref);
|
||||
let dst_dict = dst_obj.as_dict().unwrap();
|
||||
assert_eq!(dst_dict.get(b"F").and_then(|f| dst.resolve(f).as_int()), Some(4 | 128));
|
||||
let dst_bs = dst_dict.get(b"BS").map(|o| dst.resolve(o)).unwrap();
|
||||
let dst_bs = dst_bs.as_dict().unwrap();
|
||||
assert_eq!(dst_bs.name(b"S"), Some(b"D".as_slice()));
|
||||
assert_eq!(dst_bs.get(b"W").and_then(|w| dst.resolve(w).as_f64()), Some(2.5));
|
||||
}
|
||||
@@ -2,11 +2,11 @@ use super::common::{
|
||||
MAX_DEPTH, arr, check_form_xml_depth, csv, el_text, esc, hex, n, nums_of, parse_form_xml, parse_hex, quad_has_area, rect_strict, text_of,
|
||||
walk_xfdf,
|
||||
};
|
||||
use super::grammar::{
|
||||
use super::*;
|
||||
use craft_xfdf::grammar::{
|
||||
AnnotFormat, BorderStyle, CaretSymbol, SUBTYPES, format_flags, format_pairs, pairs, parse_flags, parse_format_attrs, rich_plain,
|
||||
rich_text_element, standalone, with_comment_nodes, write_format_attrs,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
// ── export ──────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in new issue
Block a user