Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions crates/paperjam-docx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,11 @@ impl DocumentTrait for DocxDocument {
}

fn save_to_bytes(&self) -> Result<Vec<u8>, Self::Error> {
let mut buf = std::io::Cursor::new(Vec::new());
self.inner
.clone()
.build()
.pack(&mut buf)
.map_err(|e| DocxError::Io(std::io::Error::other(e)))?;
Ok(buf.into_inner())
// Return the original input bytes. This crate exposes no mutation API,
// so a rebuild via `inner.build().pack()` would be lossy and — for any
// DOCX containing complex fields (TOC, PAGE, PAGEREF, HYPERLINK, …) —
// panics in docx-rs 0.4 (`RunChild::InstrTextString` is reader-only;
// its writer arm is `unreachable!()`). See bokuweb/docx-rs#750.
Ok(self.raw_bytes.clone())
}
}
13 changes: 10 additions & 3 deletions py_src/paperjam/_any_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,16 @@ def convert_to(self, format: str) -> bytes:
return bytes(self._ensure_open().convert_to(format))

def save(self, path: str | os.PathLike[str]) -> None:
"""Save the document to a file."""
data = self.save_bytes()
with builtins_open(str(path), "wb") as f:
"""Save the document to a file.

The target format is inferred from the file extension. If it differs
from the source format, the document is converted via :meth:`convert_to`;
otherwise the original bytes are written unchanged.
"""
path_str = str(path)
target_ext = os.path.splitext(path_str)[1].lstrip(".").lower()
data = self.convert_to(target_ext) if target_ext and target_ext != self.format else self.save_bytes()
with builtins_open(path_str, "wb") as f:
f.write(data)

def save_bytes(self) -> bytes:
Expand Down
Loading