diff --git a/crates/export/src/as_html.rs b/crates/export/src/as_html.rs
index 5d51e3b6fe..3610309a26 100644
--- a/crates/export/src/as_html.rs
+++ b/crates/export/src/as_html.rs
@@ -1,12 +1,10 @@
-use super::as_docx::{hex, rgb8, room_for};
-use super::layout::{Image, Item, Page, Run, Table, items};
+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};
-/// 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. Text extracted from PDFs often holds them
-/// (fonts without a usable `/ToUnicode`), and Word refuses a whole document over one (#72).
-pub(crate) fn allowed(c: char) -> bool {
- matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}')
-}
+pub(crate) use super::html::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.
@@ -43,22 +41,6 @@ pub(crate) fn language_tag(lang: Option<&str>) -> Option<&str> {
(!singleton).then_some(tag)
}
-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
-}
-
-pub(crate) use craft_mime::transfer::base64;
-
/// One HTML file: headings and paragraphs, tables as real `
` elements, images inline, a
/// rule between pages.
pub fn html(pages: &[Page], title: &str) -> String {
@@ -83,96 +65,64 @@ pub fn html_simple_with_language(pages: &[Page], title: &str, language: Option<&
html_with_mode(pages, title, true, language)
}
-fn style_color(color: [f64; 3], simple: bool) -> String {
- if simple { String::new() } else { hex(color).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) }
-}
-
-fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String {
- if text.trim().is_empty() {
- return text;
- }
- if italic {
- text = format!("{text}");
- }
- if bold {
- text = format!("{text}");
- }
- text
-}
-
+#[cfg(test)]
fn para_html(runs: &[Run<'_>], lvl: u8, simple: bool) -> Option {
- let non_empty: Vec<_> = runs.iter().map(|r| (r.block, 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 (block, text) in non_empty {
- if text.trim().is_empty() {
- t.push_str(&text);
- continue;
- }
- let mut run = wrap_inline(text, block.bold && lvl == 0, block.italic);
- // The paragraph has its first visible run's colour; a run in another colour says so.
- let colour = rgb8(block.color);
- if !simple && colour != rgb8(first.color) {
- let [red, green, blue] = colour;
- run = format!("{run}");
- }
- t.push_str(&run);
- }
- let style = style_color(first.color, simple);
- Some(match lvl.min(6) {
- 0 => format!("
");
- 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!("
{body}
"));
- }
- s.push_str("
\n");
- }
- s.push_str("
\n");
- s
+ let table = HtmlTable {
+ rows: t
+ .rows
+ .iter()
+ .map(|row| row.iter().map(|c| HtmlCell { text: &c.text, bold: c.bold, italic: c.italic, color: rgb8(c.color), span: c.span }).collect())
+ .collect(),
+ };
+ html::render_table(&table, simple)
}
fn html_with_mode(pages: &[Page], title: &str, simple: bool, language: Option<&str>) -> String {
- let lang = language_tag(language).map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default();
- let mut s = format!(
- "\n\n\n\n{}\n{}\n\n\n",
- esc(title),
- if simple {
- ""
- } else {
- ""
- }
- );
let mut embedded: Vec<(String, &Image)> = Vec::new();
- for it in items(pages) {
+ let mut blocks: Vec> = Vec::new();
+ let items: Vec> = items(pages);
+ for it in &items {
match it {
Item::Para(runs, lvl) => {
- if let Some(p) = para_html(&runs, lvl, simple) {
- s.push_str(&p);
- }
+ blocks.push(HtmlBlock::Para {
+ runs: runs
+ .iter()
+ .map(|r| HtmlRun { text: &r.text, bold: r.block.bold, italic: r.block.italic, color: rgb8(r.block.color) })
+ .collect(),
+ level: *lvl,
+ });
+ }
+ Item::Table(t) => {
+ blocks.push(HtmlBlock::Table(HtmlTable {
+ rows: t
+ .rows
+ .iter()
+ .map(|row| {
+ row.iter()
+ .map(|c| HtmlCell { text: &c.text, bold: c.bold, italic: c.italic, color: rgb8(c.color), span: c.span })
+ .collect()
+ })
+ .collect(),
+ }));
}
- Item::Table(t) => s.push_str(&table_html(&t, simple)),
// HTML embeds each placement in full, so repeated pictures also consume the budget.
Item::Img(im) if room_for(&embedded, im) => {
let mime = if im.ext == "jpg" { "image/jpeg" } else { "image/png" };
- s.push_str(&format!("
\n", base64(&im.bytes)));
+ blocks.push(HtmlBlock::Image { mime, bytes: &im.bytes });
embedded.push((String::new(), im));
}
Item::Img(_) => {}
- Item::PageBreak => s.push_str("\n"),
+ Item::PageBreak => blocks.push(HtmlBlock::PageBreak),
}
}
- s.push_str("\n\n");
- s
+ html::render(&blocks, title, simple, language_tag(language))
}
#[cfg(test)]
diff --git a/crates/export/src/html.rs b/crates/export/src/html.rs
new file mode 100644
index 0000000000..e1d88c3796
--- /dev/null
+++ b/crates/export/src/html.rs
@@ -0,0 +1,145 @@
+//! 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>>,
+}
+
+/// A block-level element in a portable HTML document.
+pub(crate) enum HtmlBlock<'a> {
+ Para { runs: Vec>, level: u8 },
+ Table(HtmlTable<'a>),
+ Image { mime: &'a str, bytes: &'a [u8] },
+ PageBreak,
+}
+
+fn rgb_hex(rgb: [u8; 3]) -> Option {
+ 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!("{text}");
+ }
+ if bold {
+ text = format!("{text}");
+ }
+ text
+}
+
+pub(crate) fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option {
+ 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!("{out}");
+ }
+ t.push_str(&out);
+ }
+ let style = style_color(first.color, simple);
+ Some(match lvl.min(6) {
+ 0 => format!("
{t}
\n"),
+ l => format!("{t}\n"),
+ })
+}
+
+pub(crate) fn render_table(t: &HtmlTable<'_>, simple: bool) -> String {
+ let mut s = String::from("
\n");
+ for row in &t.rows {
+ s.push_str("
");
+ 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!("
{body}
"));
+ }
+ s.push_str("
\n");
+ }
+ s.push_str("
\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!(
+ "\n\n\n\n{}\n{}\n\n\n",
+ esc(title),
+ if simple {
+ ""
+ } else {
+ ""
+ }
+ );
+ 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!("
\n", base64(bytes)));
+ }
+ HtmlBlock::PageBreak => s.push_str("\n"),
+ }
+ }
+ s.push_str("\n\n");
+ s
+}
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 42279325ab..3310f249d3 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -23,15 +23,13 @@ mod as_rtf;
mod as_word;
mod clip;
mod flow;
+mod html;
mod layout;
#[cfg(test)]
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)]
-use as_html::{allowed, base64};
pub use as_html::{html, html_simple, html_simple_with_language, html_with_language};
pub use as_markdown::markdown;
#[cfg(test)]
@@ -40,6 +38,9 @@ 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};
#[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};
diff --git a/crates/xfdf/src/common.rs b/crates/xfdf/src/common.rs
index 87559b5c16..7bbc73d8c3 100644
--- a/crates/xfdf/src/common.rs
+++ b/crates/xfdf/src/common.rs
@@ -105,58 +105,7 @@ pub(crate) fn el_text(el: &craft_xml::El) -> String {
.collect()
}
-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"),
-];
-
-pub(crate) fn esc(s: &str) -> String {
- let mut o = String::with_capacity(s.len());
- for c in s.chars() {
- match c {
- '&' => o.push_str("&"),
- '<' => o.push_str("<"),
- '>' => o.push_str(">"),
- '"' => o.push_str("""),
- // XML 1.0 §3.3.3 normalizes literal attribute whitespace, but not references.
- '\t' => o.push_str(" "),
- '\n' => o.push_str("
"),
- '\r' => o.push_str("
"),
- c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}
- // XML 1.0 noncharacters are not allowed even as raw text.
- '\u{FFFE}' | '\u{FFFF}' => {}
- c => o.push(c),
- }
- }
- o
-}
+pub(crate) use craft_xml::esc_attr as esc;
pub(crate) fn n(v: f64) -> String {
let s = format!("{v:.4}");
diff --git a/crates/xfdf/src/fdf.rs b/crates/xfdf/src/fdf.rs
index 28d79b3c0b..95e3b55c81 100644
--- a/crates/xfdf/src/fdf.rs
+++ b/crates/xfdf/src/fdf.rs
@@ -1,4 +1,5 @@
-use super::common::{MAX_DEPTH, SUBTYPES, rect_strict, text_of};
+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::*;
@@ -105,7 +106,7 @@ impl<'a> FdfCopy<'a> {
let stamp = dict.name(b"Subtype") == Some(b"Stamp".as_slice());
let mut out = Dict::new();
for (key, value) in dict.iter() {
- if matches!(key.as_slice(), b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key.as_slice() == b"AP" && !stamp) {
+ if fdf_annot_skip_key(key.as_slice(), stamp) {
continue;
}
self.dict_entry(&mut out, key, value, 1)?;
diff --git a/crates/xfdf/src/grammar.rs b/crates/xfdf/src/grammar.rs
new file mode 100644
index 0000000000..867cd8c535
--- /dev/null
+++ b/crates/xfdf/src/grammar.rs
@@ -0,0 +1,355 @@
+//! 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,
+ pub border_style: Option,
+ pub dashes: Option>,
+ pub cloudy_intensity: Option