Pictures and sections
Picture insertion — common size when specified
The same call supports both formats; the Common facade recognizes PNG, JPEG, GIF, and BMP file signatures when image_format is omitted. Supply image_format for unrecognized bytes (the backend may still reject unsupported formats).
"""Insert PNG bytes using a size explicit for both DOCX and HWPX."""
import base64
from pathlib import Path
from pywpdoc import Document, Mm
PNG = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
)
def run(fmt: str, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
doc = Document.new(fmt)
doc.add_paragraph("Image example")
picture = doc.add_picture(PNG, width=Mm(25.4), height=Mm(12.7))
assert abs(picture.width.mm - 25.4) < 0.05
path = out_dir / f"picture.{fmt}"
doc.save(path)
assert Document.open(path).pictures
return path
if __name__ == "__main__":
import sys
print(run(sys.argv[1], Path(sys.argv[2])))
Run: python examples/manual/pictures.py docx ./output (or hwpx). width and height accept pywpdoc.Mm or HWP units. For predictable cross-format physical sizes, always specify width and height. If width=None, DOCX uses intrinsic image size while HWPX retains its native default of 14400 HWP units (2 inches). DOCX currently supports inline pictures only (treat_as_char=False is rejected).
Unknown binary image signatures without explicit image_format raise DocumentValueError(code="common-image-format-unknown") before modifying the document.
Sections — portable subset
"""Portable section creation: no format-specific options."""
from pathlib import Path
from pywpdoc import Document
def run(fmt: str, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
doc = Document.new(fmt)
doc.add_paragraph("Section one")
section = doc.add_section() # portable, default position/start only
assert section is not None
doc.add_paragraph("Section two")
path = out_dir / f"sections.{fmt}"
doc.save(path)
return path
if __name__ == "__main__":
import sys
print(run(sys.argv[1], Path(sys.argv[2])))
The portable contract is doc.add_section() without options. DOCX has start_type, while HWPX has after; neither is accepted by the portable method. Use the matching format-specific API when such controls are required. Resulting page layout and section-start pagination can differ.