python-docx-oss 0.5.0__py3-none-any.whl → 0.5.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
docx/__init__.py CHANGED
@@ -15,7 +15,7 @@ from docx.transforms import normalize, repair
15
15
  if TYPE_CHECKING:
16
16
  from docx.opc.part import Part
17
17
 
18
- __version__ = "0.5.0"
18
+ __version__ = "0.5.2"
19
19
 
20
20
 
21
21
  __all__ = [
docx/enum/table.py CHANGED
@@ -1,5 +1,7 @@
1
1
  """Enumerations related to tables in WordprocessingML files."""
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  from docx.enum.base import BaseEnum, BaseXmlEnum
4
6
 
5
7
 
@@ -106,6 +108,14 @@ class WD_TABLE_ALIGNMENT(BaseXmlEnum):
106
108
  RIGHT = (2, "right", "Right-aligned.")
107
109
  """Right-aligned."""
108
110
 
111
+ @classmethod
112
+ def from_xml(cls, xml_value: str | None) -> WD_TABLE_ALIGNMENT:
113
+ if xml_value == "start":
114
+ return cls.LEFT
115
+ if xml_value == "end":
116
+ return cls.RIGHT
117
+ return super().from_xml(xml_value)
118
+
109
119
 
110
120
  class WD_TABLE_DIRECTION(BaseEnum):
111
121
  """Specifies the direction in which an application orders cells in the specified
docx/enum/text.py CHANGED
@@ -63,6 +63,14 @@ class WD_PARAGRAPH_ALIGNMENT(BaseXmlEnum):
63
63
  )
64
64
  """Justified according to Thai formatting layout."""
65
65
 
66
+ @classmethod
67
+ def from_xml(cls, xml_value: str | None) -> WD_PARAGRAPH_ALIGNMENT:
68
+ if xml_value == "start":
69
+ return cls.LEFT
70
+ if xml_value == "end":
71
+ return cls.RIGHT
72
+ return super().from_xml(xml_value)
73
+
66
74
 
67
75
  WD_ALIGN_PARAGRAPH = WD_PARAGRAPH_ALIGNMENT
68
76
 
docx/inspection/reader.py CHANGED
@@ -19,13 +19,11 @@ from docx.inspection.result import (
19
19
  RelationshipInventory,
20
20
  )
21
21
  from docx.inspection.source import PackageSource, open_source
22
+ from docx.opc.constants import STRICT_REL_BASE, TRANSITIONAL_REL_BASE
22
23
 
23
24
  CT_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
24
25
  REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
25
- OFFICE_REL_BASES = (
26
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/",
27
- "http://purl.oclc.org/ooxml/officeDocument/relationships/",
28
- )
26
+ OFFICE_REL_BASES = (TRANSITIONAL_REL_BASE, STRICT_REL_BASE)
29
27
  PACKAGE_ERRORS = (
30
28
  BadZipFile,
31
29
  EOFError,
docx/opc/constants.py CHANGED
@@ -305,3 +305,7 @@ class RELATIONSHIP_TYPE:
305
305
  "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheetSource"
306
306
  )
307
307
  XML_MAPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/xmlMaps"
308
+
309
+
310
+ TRANSITIONAL_REL_BASE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
311
+ STRICT_REL_BASE = "http://purl.oclc.org/ooxml/officeDocument/relationships/"
docx/opc/phys_pkg.py CHANGED
@@ -1,10 +1,165 @@
1
1
  """Provides a general interface to a `physical` OPC package, such as a zip file."""
2
2
 
3
3
  import os
4
+ import re
5
+ from html import unescape
6
+ from xml.sax.saxutils import escape
4
7
  from zipfile import ZIP_DEFLATED, ZipFile, is_zipfile
5
8
 
9
+ from lxml import etree
10
+
6
11
  from docx.opc.exceptions import PackageNotFoundError
7
- from docx.opc.packuri import CONTENT_TYPES_URI
12
+ from docx.opc.packuri import CONTENT_TYPES_URI, PackURI
13
+
14
+ _STRICT_TO_TRANSITIONAL_MAPPINGS = (
15
+ # Hyphenated differences in Transitional relationships and parts:
16
+ (
17
+ "http://purl.oclc.org/ooxml/officeDocument/relationships/extendedProperties",
18
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",
19
+ ),
20
+ (
21
+ "http://purl.oclc.org/ooxml/officeDocument/relationships/customProperties",
22
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties",
23
+ ),
24
+ (
25
+ "http://purl.oclc.org/ooxml/officeDocument/extendedProperties",
26
+ "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
27
+ ),
28
+ (
29
+ "http://purl.oclc.org/ooxml/officeDocument/customProperties",
30
+ "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
31
+ ),
32
+ # General officeDocument rule (covers relationships, math, customXml, etc.):
33
+ (
34
+ "http://purl.oclc.org/ooxml/officeDocument/",
35
+ "http://schemas.openxmlformats.org/officeDocument/2006/",
36
+ ),
37
+ # Domain packages:
38
+ (
39
+ "http://purl.oclc.org/ooxml/wordprocessingml/",
40
+ "http://schemas.openxmlformats.org/wordprocessingml/2006/",
41
+ ),
42
+ (
43
+ "http://purl.oclc.org/ooxml/drawingml/",
44
+ "http://schemas.openxmlformats.org/drawingml/2006/",
45
+ ),
46
+ (
47
+ "http://purl.oclc.org/ooxml/spreadsheetml/",
48
+ "http://schemas.openxmlformats.org/spreadsheetml/2006/",
49
+ ),
50
+ (
51
+ "http://purl.oclc.org/ooxml/presentationml/",
52
+ "http://schemas.openxmlformats.org/presentationml/2006/",
53
+ ),
54
+ (
55
+ "http://purl.oclc.org/ooxml/schemaLibrary/",
56
+ "http://schemas.openxmlformats.org/schemaLibrary/2006/",
57
+ ),
58
+ )
59
+
60
+
61
+ def _transitional_uri(uri: str) -> str:
62
+ for strict_base, transitional_base in _STRICT_TO_TRANSITIONAL_MAPPINGS:
63
+ if uri.startswith(strict_base):
64
+ return transitional_base + uri[len(strict_base) :]
65
+ return uri
66
+
67
+
68
+ # Match whole XML tokens so apparent tags inside comments, CDATA, and PIs stay opaque.
69
+ _XML_TOKEN = re.compile(
70
+ r"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>|</?[^\s<>/]+(?:[^<>\"']|\"[^\"]*\"|'[^']*')*>",
71
+ re.DOTALL,
72
+ )
73
+ _XML_ATTRIBUTE = re.compile(r"([^\s=<>/]+)(\s*=\s*)([\"'])(.*?)\3", re.DOTALL)
74
+ _XML_NAME = re.compile(r"</?([^\s/>]+)")
75
+ _WML_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
76
+ _DRAWING_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
77
+ _REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
78
+
79
+
80
+ def _normalize_strict_blob(pack_uri: PackURI, blob: bytes) -> bytes:
81
+ """Normalize selected XML attributes without rebuilding or reserializing the tree.
82
+
83
+ Namespace scopes identify semantic attributes regardless of prefix. Text,
84
+ comments, CDATA, unrelated attributes, and original formatting are preserved.
85
+ Malformed or DTD-bearing opaque parts are passed through unchanged.
86
+ """
87
+ if not pack_uri.membername.endswith((".xml", ".rels")):
88
+ return blob
89
+ if b"http://purl.oclc.org/ooxml/" not in blob.replace(b"\x00", b""):
90
+ return blob
91
+ try:
92
+ root = etree.fromstring(blob, etree.XMLParser(resolve_entities=False))
93
+ if root.getroottree().docinfo.doctype:
94
+ return blob
95
+ if blob.startswith((b"\xff\xfe", b"<\x00")):
96
+ encoding = "utf-16-le"
97
+ elif blob.startswith((b"\xfe\xff", b"\x00<")):
98
+ encoding = "utf-16-be"
99
+ else:
100
+ encoding = "utf-8"
101
+ xml = blob.decode(encoding)
102
+ except (etree.XMLSyntaxError, UnicodeError, ValueError):
103
+ return blob
104
+
105
+ scopes: list[dict[str, str]] = [{}]
106
+
107
+ def convert_tag(match: re.Match[str]) -> str:
108
+ tag = match.group()
109
+ if tag.startswith(("<!", "<?")):
110
+ return tag
111
+ if tag.startswith("</"):
112
+ scopes.pop()
113
+ return tag
114
+ scope = scopes[-1]
115
+ if "xmlns" in tag:
116
+ scope = scope.copy()
117
+ for attr in _XML_ATTRIBUTE.finditer(tag):
118
+ name, _, _, value = attr.groups()
119
+ if name == "xmlns" or name.startswith("xmlns:"):
120
+ scope[name.partition(":")[2]] = unescape(value)
121
+ if not tag.endswith("/>"):
122
+ scopes.append(scope)
123
+ if "http://purl.oclc.org/ooxml/" not in tag and "conformance" not in tag:
124
+ return tag
125
+ name_match = _XML_NAME.match(tag)
126
+ assert name_match is not None
127
+ prefix, separator, local = name_match[1].rpartition(":")
128
+ element_ns = _transitional_uri(scope.get(prefix if separator else "", ""))
129
+
130
+ def convert_attribute(attr: re.Match[str]) -> str:
131
+ name, equals, quote, value = attr.groups()
132
+ decoded = unescape(value)
133
+ converted = decoded
134
+ if (
135
+ name == "xmlns"
136
+ or name.startswith("xmlns:")
137
+ or (element_ns == _REL_NS and local == "Relationship" and name == "Type")
138
+ or (element_ns == _DRAWING_NS and local == "graphicData" and name == "uri")
139
+ ):
140
+ converted = _transitional_uri(decoded)
141
+ elif ":" in name:
142
+ prefix, _, attr_local = name.partition(":")
143
+ if (
144
+ _transitional_uri(scope.get(prefix, "")) == _WML_NS
145
+ and attr_local == "conformance"
146
+ and decoded == "strict"
147
+ ):
148
+ converted = "transitional"
149
+ if converted == decoded:
150
+ return attr.group()
151
+ return (
152
+ name
153
+ + equals
154
+ + quote
155
+ + escape(converted, {quote: "&quot;" if quote == '"' else "&apos;"})
156
+ + quote
157
+ )
158
+
159
+ return _XML_ATTRIBUTE.sub(convert_attribute, tag)
160
+
161
+ normalized = _XML_TOKEN.sub(convert_tag, xml)
162
+ return blob if normalized == xml else normalized.encode(encoding)
8
163
 
9
164
 
10
165
  class PhysPkgReader:
@@ -46,7 +201,7 @@ class _DirPkgReader(PhysPkgReader):
46
201
  path = os.path.join(self._path, pack_uri.membername)
47
202
  with open(path, "rb") as f:
48
203
  blob = f.read()
49
- return blob
204
+ return _normalize_strict_blob(pack_uri, blob)
50
205
 
51
206
  def close(self):
52
207
  """Provides interface consistency with |ZipFileSystem|, but does nothing, a
@@ -80,7 +235,7 @@ class _ZipPkgReader(PhysPkgReader):
80
235
 
81
236
  Raises |ValueError| if no matching member is present in zip archive.
82
237
  """
83
- return self._zipf.read(pack_uri.membername)
238
+ return _normalize_strict_blob(pack_uri, self._zipf.read(pack_uri.membername))
84
239
 
85
240
  def close(self):
86
241
  """Close the zip archive, releasing any resources it is using."""
docx/oxml/simpletypes.py CHANGED
@@ -424,6 +424,29 @@ class ST_UniversalMeasure(BaseSimpleType):
424
424
  return Emu(int(round(quantity * multiplier)))
425
425
 
426
426
 
427
+ class ST_MeasurementOrPercent(BaseSimpleType):
428
+ """Corresponds to ST_MeasurementOrPercent in WML.
429
+
430
+ Can be a universal measure (e.g. '231.60pt'), an integer or float string
431
+ interpreted as twips (e.g. '1440'), or a percentage string (e.g. '25%').
432
+ """
433
+
434
+ @classmethod
435
+ def convert_from_xml(cls, str_value: str) -> Length | str:
436
+ if str_value.endswith("%"):
437
+ return str_value
438
+ if any(unit in str_value for unit in ("mm", "cm", "in", "pt", "pc", "pi")):
439
+ return ST_UniversalMeasure.convert_from_xml(str_value)
440
+ return Twips(int(round(float(str_value))))
441
+
442
+ @classmethod
443
+ def convert_to_xml(cls, value: int | Length | str) -> str:
444
+ if isinstance(value, str):
445
+ return value
446
+ emu = Emu(value)
447
+ return str(emu.twips)
448
+
449
+
427
450
  class ST_VerticalAlignRun(XsdStringEnumeration):
428
451
  """Valid values for `w:vertAlign/@val`."""
429
452
 
docx/oxml/table.py CHANGED
@@ -10,11 +10,11 @@ from docx.oxml.ns import nsdecls, qn
10
10
  from docx.oxml.parser import parse_xml
11
11
  from docx.oxml.shared import CT_DecimalNumber
12
12
  from docx.oxml.simpletypes import (
13
+ ST_MeasurementOrPercent,
13
14
  ST_Merge,
14
15
  ST_TblLayoutType,
15
16
  ST_TblWidth,
16
17
  ST_TwipsMeasure,
17
- XsdInt,
18
18
  )
19
19
  from docx.oxml.text.paragraph import CT_P
20
20
  from docx.oxml.xmlchemy import (
@@ -26,7 +26,7 @@ from docx.oxml.xmlchemy import (
26
26
  ZeroOrMore,
27
27
  ZeroOrOne,
28
28
  )
29
- from docx.shared import Emu, Length, Twips
29
+ from docx.shared import Emu, Length
30
30
 
31
31
  if TYPE_CHECKING:
32
32
  from docx.enum.table import WD_TABLE_ALIGNMENT
@@ -399,10 +399,9 @@ class CT_TblPrEx(BaseOxmlElement):
399
399
  class CT_TblWidth(BaseOxmlElement):
400
400
  """Used for `w:tblW` and `w:tcW` and others, specifies a table-related width."""
401
401
 
402
- # the type for `w` attr is actually ST_MeasurementOrPercent, but using
403
- # XsdInt for now because only dxa (twips) values are being used. It's not
404
- # entirely clear what the semantics are for other values like -01.4mm
405
- w: int = RequiredAttribute("w:w", XsdInt) # pyright: ignore[reportAssignmentType]
402
+ w: Length | str = RequiredAttribute( # pyright: ignore[reportAssignmentType]
403
+ "w:w", ST_MeasurementOrPercent
404
+ )
406
405
  type = RequiredAttribute("w:type", ST_TblWidth)
407
406
 
408
407
  @property
@@ -410,12 +409,13 @@ class CT_TblWidth(BaseOxmlElement):
410
409
  """EMU length indicated by the combined `w:w` and `w:type` attrs."""
411
410
  if self.type != "dxa":
412
411
  return None
413
- return Twips(self.w)
412
+ w = self.w
413
+ return w if isinstance(w, Length) else None
414
414
 
415
415
  @width.setter
416
416
  def width(self, value: Length):
417
417
  self.type = "dxa"
418
- self.w = Emu(value).twips
418
+ self.w = value
419
419
 
420
420
 
421
421
  class CT_Tc(BaseOxmlElement):
docx/oxml/text/parfmt.py CHANGED
@@ -29,6 +29,12 @@ if TYPE_CHECKING:
29
29
  class CT_Ind(BaseOxmlElement):
30
30
  """``<w:ind>`` element, specifying paragraph indentation."""
31
31
 
32
+ start: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
33
+ "w:start", ST_SignedTwipsMeasure
34
+ )
35
+ end: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
36
+ "w:end", ST_SignedTwipsMeasure
37
+ )
32
38
  left: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
33
39
  "w:left", ST_SignedTwipsMeasure
34
40
  )
@@ -152,10 +158,12 @@ class CT_PPr(BaseOxmlElement):
152
158
 
153
159
  @property
154
160
  def ind_left(self) -> Length | None:
155
- """The value of `w:ind/@w:left` or |None| if not present."""
161
+ """The value of `w:ind/@w:start` or `w:ind/@w:left` or |None| if not present."""
156
162
  ind = self.ind
157
163
  if ind is None:
158
164
  return None
165
+ if ind.start is not None:
166
+ return ind.start
159
167
  return ind.left
160
168
 
161
169
  @ind_left.setter
@@ -164,13 +172,17 @@ class CT_PPr(BaseOxmlElement):
164
172
  return
165
173
  ind = self.get_or_add_ind()
166
174
  ind.left = value
175
+ if ind.start is not None:
176
+ ind.start = None
167
177
 
168
178
  @property
169
179
  def ind_right(self) -> Length | None:
170
- """The value of `w:ind/@w:right` or |None| if not present."""
180
+ """The value of `w:ind/@w:end` or `w:ind/@w:right` or |None| if not present."""
171
181
  ind = self.ind
172
182
  if ind is None:
173
183
  return None
184
+ if ind.end is not None:
185
+ return ind.end
174
186
  return ind.right
175
187
 
176
188
  @ind_right.setter
@@ -179,6 +191,8 @@ class CT_PPr(BaseOxmlElement):
179
191
  return
180
192
  ind = self.get_or_add_ind()
181
193
  ind.right = value
194
+ if ind.end is not None:
195
+ ind.end = None
182
196
 
183
197
  @property
184
198
  def jc_val(self) -> WD_ALIGN_PARAGRAPH | None:
docx/text/parfmt.py CHANGED
@@ -81,7 +81,7 @@ class ParagraphFormat(ElementProxy):
81
81
  self._element.get_or_add_pPr().keepNext_val = value
82
82
 
83
83
  @property
84
- def left_indent(self):
84
+ def left_indent(self) -> Length | None:
85
85
  """|Length| value specifying the space between the left margin and the left side
86
86
  of the paragraph.
87
87
 
@@ -95,7 +95,7 @@ class ParagraphFormat(ElementProxy):
95
95
  return pPr.ind_left
96
96
 
97
97
  @left_indent.setter
98
- def left_indent(self, value):
98
+ def left_indent(self, value: Length | None) -> None:
99
99
  pPr = self._element.get_or_add_pPr()
100
100
  pPr.ind_left = value
101
101
 
@@ -176,7 +176,7 @@ class ParagraphFormat(ElementProxy):
176
176
  self._element.get_or_add_pPr().pageBreakBefore_val = value
177
177
 
178
178
  @property
179
- def right_indent(self):
179
+ def right_indent(self) -> Length | None:
180
180
  """|Length| value specifying the space between the right margin and the right
181
181
  side of the paragraph.
182
182
 
@@ -190,7 +190,7 @@ class ParagraphFormat(ElementProxy):
190
190
  return pPr.ind_right
191
191
 
192
192
  @right_indent.setter
193
- def right_indent(self, value):
193
+ def right_indent(self, value: Length | None) -> None:
194
194
  pPr = self._element.get_or_add_pPr()
195
195
  pPr.ind_right = value
196
196
 
@@ -17,6 +17,8 @@ W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
17
17
  R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
18
18
  XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
19
19
  Selector = Callable[[HyperlinkTarget], bool]
20
+ _ARGUMENT_SWITCHES = frozenset((r"\l", r"\o", r"\t", r"\*"))
21
+ _SUPPORTED_SWITCHES = _ARGUMENT_SWITCHES | {r"\h"}
20
22
 
21
23
 
22
24
  def w(name: str) -> str:
@@ -29,6 +31,7 @@ class _Instruction:
29
31
  anchor: str | None
30
32
  tooltip: str | None = None
31
33
  frame: str | None = None
34
+ has_h_switch: bool = False
32
35
 
33
36
 
34
37
  def _instruction(text: str) -> _Instruction | None:
@@ -41,13 +44,19 @@ def _instruction(text: str) -> _Instruction | None:
41
44
  address = tokens[index][0]
42
45
  index += 1
43
46
  options: dict[str, str] = {}
47
+ has_h_switch = False
44
48
  while index < len(tokens):
45
49
  key, quoted = tokens[index]
46
50
  key = key.lower()
47
51
  index += 1
52
+ if key == "\\h" and not quoted:
53
+ if has_h_switch:
54
+ return None
55
+ has_h_switch = True
56
+ continue
48
57
  if (
49
58
  quoted
50
- or key not in ("\\l", "\\o", "\\t", "\\*")
59
+ or key not in _ARGUMENT_SWITCHES
51
60
  or index == len(tokens)
52
61
  or not tokens[index][1]
53
62
  and tokens[index][0].startswith("\\")
@@ -61,7 +70,13 @@ def _instruction(text: str) -> _Instruction | None:
61
70
  anchor = options.get("\\l")
62
71
  if not address and not anchor:
63
72
  return None
64
- return _Instruction(address or None, anchor, options.get("\\o"), options.get("\\t"))
73
+ return _Instruction(
74
+ address or None,
75
+ anchor,
76
+ options.get("\\o"),
77
+ options.get("\\t"),
78
+ has_h_switch=has_h_switch,
79
+ )
65
80
 
66
81
 
67
82
  def _field_tokens(text: str) -> list[tuple[str, bool]] | None:
@@ -96,7 +111,7 @@ def _field_tokens(text: str) -> list[tuple[str, bool]] | None:
96
111
  while index < len(text) and not text[index].isspace():
97
112
  index += 1
98
113
  token = text[start:index]
99
- if '"' in token or "\\" in token and token.lower() not in ("\\l", "\\o", "\\t", "\\*"):
114
+ if '"' in token or "\\" in token and token.lower() not in _SUPPORTED_SWITCHES:
100
115
  return None
101
116
  tokens.append((token, False))
102
117
  return tokens
@@ -176,6 +191,8 @@ class HyperlinkNormalizer:
176
191
  ):
177
192
  if value is not None:
178
193
  link.set(w(name), value)
194
+ if instruction.has_h_switch:
195
+ link.set(w("history"), "false")
179
196
  return link
180
197
 
181
198
  def _protected(self, element: etree_Element) -> bool:
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-docx-oss
3
+ Version: 0.5.2
4
+ Summary: Create, read, and update Microsoft Word .docx files.
5
+ Author: Ethan St Lee
6
+ License-Expression: MIT
7
+ Project-URL: Changelog, https://github.com/lsaint/python-docx-oss/blob/master/HISTORY.md
8
+ Project-URL: Documentation, https://python-docx-oss.readthedocs.io/en/latest/
9
+ Project-URL: Issues, https://github.com/lsaint/python-docx-oss/issues
10
+ Project-URL: Repository, https://github.com/lsaint/python-docx-oss
11
+ Keywords: docx,office,openxml,word
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Office/Business :: Office Suites
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Requires-Python: >=3.12
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: lxml>=6.1.0
27
+ Requires-Dist: typing_extensions>=4.9.0
28
+ Dynamic: license-file
29
+
30
+ <p align="center">
31
+ <img src="https://raw.githubusercontent.com/lsaint/python-docx-oss/master/docs/_static/img/oss.png" width="400" alt="python-docx-oss"/>
32
+ </p>
33
+
34
+ <p align="center">
35
+ <strong>A Python SDK for advanced creation and manipulation of Microsoft Word <code>.docx</code> files.</strong>
36
+ </p>
37
+
38
+ <p align="center">
39
+ <a href="https://pypi.org/project/python-docx-oss/"><img alt="PyPI" src="https://img.shields.io/pypi/v/python-docx-oss"></a>
40
+ <a href="https://pypi.org/project/python-docx-oss/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/python-docx-oss.svg"></a>
41
+ <a href="https://github.com/astral-sh/ruff"><img alt="Code style: Ruff" src="https://img.shields.io/badge/code%20style-ruff-FF6B6B.svg?logo=ruff&logoColor=white"></a>
42
+ <a href="https://github.com/lsaint/python-docx-oss/blob/master/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a>
43
+ </p>
44
+
45
+ ## Overview
46
+
47
+ `python-docx-oss` is an independently evolving DOCX SDK built on the proven API
48
+ foundation of [`python-docx`](https://github.com/python-openxml/python-docx). It keeps
49
+ the familiar `docx` programming model while extending it for advanced OOXML and Open
50
+ Packaging Convention (OPC) workflows.
51
+
52
+ Use it when an application needs more than basic paragraphs and tables: custom document
53
+ metadata, application-owned XML, vector images, floating pictures, East Asian fonts,
54
+ package inspection, configurable fingerprints, repair, or low-level package and relationship access.
55
+
56
+ [Documentation](https://python-docx-oss.readthedocs.io/en/latest/) · [API Reference](docs/index.rst#api-documentation) · [Release History](HISTORY.md)
57
+
58
+ ## Capability Matrix
59
+
60
+ | Capability | Primary API / Behavior |
61
+ | --- | --- |
62
+ | **Major additions** | |
63
+ | [Custom document properties](docs/user/custom-properties.rst) | `document.custom_properties` |
64
+ | [Custom XML lifecycle](docs/user/custom-xml.rst) | `add_custom_xml_part()`, `delete_custom_xml_part()` |
65
+ | [SVG and EMF images](docs/user/shapes.rst) | `add_picture()` |
66
+ | [Floating pictures](docs/user/shapes.rst) | `add_float_picture()` |
67
+ | [Latin and East Asian font controls](docs/user/text.rst) | `run.font.name`, `run.font.hAnsi`, `run.font.eastAsia` |
68
+ | [Low-level OPC parts and relationships](docs/user/api-concepts.rst) | `document.part.package`, `part.rels` |
69
+ | [In-memory read, export, and independent copies](docs/user/documents.rst) | `Document(bytes)`, `to_bytes()`, `copy()` |
70
+ | [Document sanitization](docs/user/sanitization.rst) | `document.sanitize()` |
71
+ | [Read-only package inspection and streaming feature scanning](docs/user/inspection.rst) | `inspect()`, `ScanEvent` |
72
+ | [Configurable package-content fingerprints](docs/user/inspection.rst#content-fingerprints) | `fingerprint()`, `FingerprintPolicy`, `serialize_xml` |
73
+ | [Explicit empty Custom XML repair and hyperlink normalization](docs/user/transformations.rst) | `repair()`, `normalize()` |
74
+ | **Major fixes and compatibility** | |
75
+ | [Strict Open XML compatibility](HISTORY.md#release-history) | Open Strict documents through `Document()` with transparent package normalization |
76
+ | [Table width and logical layout compatibility](HISTORY.md#release-history) | Read measurement and percentage widths, logical indentation, and `start` / `end` alignment |
77
+ | [lxml text extraction](docs/user/compatibility.rst#preservation-of-lxml-element-text-and-itertext-semantics) | Prevent duplicate `itertext()` output; preserve public `.text` APIs |
78
+
79
+ ## Installation
80
+
81
+ ```bash
82
+ python -m pip install python-docx-oss
83
+ ```
84
+
85
+ The distribution name is `python-docx-oss`, but the Python import namespace remains
86
+ `docx`:
87
+
88
+ ```python
89
+ from docx import Document
90
+ ```
91
+
92
+ > [!WARNING]
93
+ > `python-docx` and `python-docx-oss` provide the same `docx` import namespace. Do not
94
+ > install both distributions in the same Python environment.
95
+
96
+ ## Quick Start
97
+
98
+ Prepare a sharing copy with custom metadata, East Asian fonts, and a content fingerprint:
99
+
100
+ ```python
101
+ from docx import Document, fingerprint
102
+
103
+ internal = Document("internal-report.docx")
104
+ public = internal.copy() # Keep the original unchanged.
105
+
106
+ public.custom_properties["distribution"] = "public" # Set document metadata.
107
+ public.part.add_custom_xml_part('<report xmlns="urn:example:reports" id="Q4"/>')
108
+ public.add_paragraph().add_run("中文内容").font.eastAsia = "Microsoft YaHei"
109
+
110
+ public.sanitize(personal_metadata=True, comments=True) # Remove private info.
111
+ content = public.to_bytes() # Export without temporary files.
112
+ digest = fingerprint(content) # Compute a normalized package-content fingerprint.
113
+ ```
114
+
115
+ ## Compatibility and Scope
116
+
117
+ - The project maintains broad compatibility with the public `python-docx` API while
118
+ following its own versioning and product roadmap.
119
+ - Compatibility does not extend to every private or internal `python-docx` API. Test
120
+ those integrations before migrating production systems.
121
+ - The SDK focuses exclusively on DOCX. It is not a general XLSX/PPTX Office suite.
122
+ - It edits document structure but does not implement Word's page-layout rendering
123
+ engine.
124
+ - CLI, MCP, web, desktop, and Agent runtimes belong in separate packages that consume
125
+ this SDK.
126
+
127
+ ## Why “OSS”?
128
+
129
+ In Brazilian jiu-jitsu, “oss” is a greeting and an expression of respect. It reflects
130
+ the same spirit of discipline and collaboration behind this project.
131
+
132
+ ## Support
133
+
134
+ If this project is useful to you, you can support its continued development through
135
+ the [donation page](https://lsaint.github.io/donation/?utm_source=github&utm_medium=readme&utm_campaign=python-docx-oss).
@@ -1,4 +1,4 @@
1
- docx/__init__.py,sha256=EbGuaQP9wLIAJnTxqVqPgv3Vxy_AT4gU-BrQxudxGTM,2389
1
+ docx/__init__.py,sha256=nN-TGDFrKx5bxPep8otvrWNZgnj6hFT7AtMi-5NyzkU,2389
2
2
  docx/api.py,sha256=jIojXW4IRDEXQqaqvmOZbzBvNeyRXv9ntHByxd-Kb0M,1518
3
3
  docx/blkcntnr.py,sha256=_xe7Uz3RBCz4TPKXpIzRxtGg-1YPb3gAG9YvsSUyoLU,3525
4
4
  docx/comments.py,sha256=MmaP7U9mZOUFsRhaZNIbXatqOOA8-pOC6UlqWAuTHsc,6385
@@ -21,8 +21,8 @@ docx/enum/dml.py,sha256=DqqkYxl09iXQgDNZxxl_wi_n9rA7mTokde1TpO3ygmU,3346
21
21
  docx/enum/section.py,sha256=mNN1kF1mdIJQ82XFFZnd3yXXnCu5mfnXzopalnmPCqo,2391
22
22
  docx/enum/shape.py,sha256=DKQm6J3Is2050bT5RseUpwPHZZl9at0OAQjU1ha2H4g,396
23
23
  docx/enum/style.py,sha256=Z9cBR7N3mCmZ54nKJxKqPhR4SMy_hqJRH2yabDxRLo8,10137
24
- docx/enum/table.py,sha256=7PuQ--PGnSaNiE0Bu4VJ9t6LOgM-hNNmKEcl-3S2eUk,3943
25
- docx/enum/text.py,sha256=o6bdpJot2iY40UnnBQ1uGfdE8oHFm3dtXUrmt9eMlvE,10276
24
+ docx/enum/table.py,sha256=vogbHXTM-jA7gLYZWdVfL4C2AxwDduKPZ7v5n0mFciY,4229
25
+ docx/enum/text.py,sha256=OeVYyAxmTh_t5zahBD0EYBMV7tmf3KsiFLpmWYpPbBA,10530
26
26
  docx/image/__init__.py,sha256=OvnRg5_DTmmrJObUBWLVcPFMRPb-u63e0EKfF_eIQlk,924
27
27
  docx/image/bmp.py,sha256=w_Jhu6hByAckJNyKhI3zHOKsHyibHgxDIjiPI9ev704,1347
28
28
  docx/image/constants.py,sha256=c6Mtsy38b0nilCcRp9vvXkV7hyLDb0sDHfJoPqH-lPk,3490
@@ -39,11 +39,11 @@ docx/inspection/__init__.py,sha256=OVG8qDwe-l_COQIFX3hgc5vWsTEKZxtPUhk3gfbx1G0,6
39
39
  docx/inspection/_structural_xml_tags.py,sha256=aZy7B6V_SNksFoHSNfTCeBo9rPVd0uVUam6UEjtZdco,41619
40
40
  docx/inspection/features.py,sha256=rsAzh1w7YZUHGhb58yCkXBPn7kSvKdC68qJz4k0OcdU,3365
41
41
  docx/inspection/fingerprint.py,sha256=ds0pUzgyIBcLlyp1_YovOTdhN_KJ9llIPWLF_vsngo0,14309
42
- docx/inspection/reader.py,sha256=L6pTHwAN8Jn3sbeo0foJ0wEhsS5hTcTtgFUYnDd7Oog,11654
42
+ docx/inspection/reader.py,sha256=gRff7s2EjmJ3yaG6TgJbM-2SdRtqDG4kRn3oNVr4X60,11621
43
43
  docx/inspection/result.py,sha256=h6Wzm8VvSSMCxYrAwDrEisCqWFLAFq3sQRkeH7rtRRc,1440
44
44
  docx/inspection/source.py,sha256=gWkS1Gk-aZAldwUX8WG8p7MPSjz7ux9FjnA03ElqWSU,1398
45
45
  docx/opc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
46
- docx/opc/constants.py,sha256=u7JE0q95EFiAp3jXOntjv1cV0GdGpKtLfx85D2mlch0,17124
46
+ docx/opc/constants.py,sha256=PwhChn10Fp0964d2BUauISG8XVuKGWGoA3fe_i8WCg4,17298
47
47
  docx/opc/coreprops.py,sha256=DUE7xnk0syV2EtwHtJimX5V5efDccsqoB2KW_mmuHEA,4937
48
48
  docx/opc/customprops.py,sha256=oCHxWPNWSekBQrtO07WPSb0WKLQgTgfS3y8m8ZUXN-A,1986
49
49
  docx/opc/exceptions.py,sha256=pqa1GuFxMlGZDBgGBqntZ_8aDINLwo2gtPuNRwADzyM,264
@@ -51,7 +51,7 @@ docx/opc/oxml.py,sha256=IE3H4F-DWr8QSZi0pxc767apU3Nk-BhFTs7HiTD5ck0,8325
51
51
  docx/opc/package.py,sha256=zWteqHOyPbR4mpcoOZy-sPVWvQR2e2fQVoYdjaHXXfI,10217
52
52
  docx/opc/packuri.py,sha256=1-uRAwjIftl475nozvssEoS-0EBz0w-oJvT-fNYcx9o,3729
53
53
  docx/opc/part.py,sha256=WZsVGi25sZhRobXEFRBQCVX6EXan2pE1GPe_zH5nhxk,9977
54
- docx/opc/phys_pkg.py,sha256=-eNZDBbLShHo3W1iglf1CwN_nkK8qnmTWp6ABg77cjA,4005
54
+ docx/opc/phys_pkg.py,sha256=H2VYEV-9cvt-jpWpLNZnXYtQsvfX_fq6P40CmG2AYEs,10110
55
55
  docx/opc/pkgreader.py,sha256=iUPZ7Ba4kNXjPB-q1mQEO44eVmbnP08po4WFH-HD2IE,9588
56
56
  docx/opc/pkgwriter.py,sha256=shDeuBtW2BbFOTHrXx8R97PWFaH_fE37JYBfbw6QWRs,4524
57
57
  docx/opc/rel.py,sha256=ziqjJ_zQZ1Ow1sNM46se8F6YZRVST-Z8Z4NYvnnOt8o,6423
@@ -74,9 +74,9 @@ docx/oxml/section.py,sha256=ny6fhO5p4XE16CjmXgsV2f_LUhyI_d0vfnxyYznq3I4,20395
74
74
  docx/oxml/settings.py,sha256=eayU_BPA6_SGvIE-u7lnWuuK5esSVrBi6X5UnqaHlHs,4264
75
75
  docx/oxml/shape.py,sha256=9v1x1Un6SawEAjkHLxkC0LyA8TDmT7xplWIYleQJt-0,13476
76
76
  docx/oxml/shared.py,sha256=iAqDOcy-DnOm5GGsSZXLSemNejSqCjlzhB86lPEtDYM,1857
77
- docx/oxml/simpletypes.py,sha256=2pD4vgEZThJpCB4M-L8hP7uTIXglndlZRdNruvDZwm0,13019
77
+ docx/oxml/simpletypes.py,sha256=lCKt0HXrlKAiniI7DyjmdmBYJtfMt29tq-dx8EN5RrQ,13829
78
78
  docx/oxml/styles.py,sha256=1U24kcC9hhzMPzNcg19RVCUJl1_qWauXCJIHG_Kp0Io,10643
79
- docx/oxml/table.py,sha256=qS46a_Ts3KzNygUNeUxaTIVNDJZbbWNJqMseo3ZVaRA,33610
79
+ docx/oxml/table.py,sha256=1lOD4uidCGtrnHeTXlAVT4oP1HMn-Yaa83SN4yF59IQ,33464
80
80
  docx/oxml/xmlchemy.py,sha256=QFJNxaM6YQeozA238LNhRu_1j_NqZgta7aiPxCsQ0Rs,26192
81
81
  docx/oxml/dml/CT_ExtensionList.py,sha256=drQvDl9Zo10H1JMtHdI8AUxlX0U0NFPKwIyHAlUhDTk,1216
82
82
  docx/oxml/text/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -84,7 +84,7 @@ docx/oxml/text/font.py,sha256=s5MJwoei24s1xdhtsI1P02wqI6mLpvkLTCXr73EWNWI,11900
84
84
  docx/oxml/text/hyperlink.py,sha256=wcyip51zHHPPCLFRVBGmItFf6xxOYI8QD0Jyvjrzx4c,1416
85
85
  docx/oxml/text/pagebreak.py,sha256=1iK12GAowZpFRjVAmnZ_Mpqn7O0PqPSrVc2myUc4KM4,11192
86
86
  docx/oxml/text/paragraph.py,sha256=eIopq-H6EbtCPxWbiS_wBSf8RvZeQ2Q7OJv7-Hyt3gM,3494
87
- docx/oxml/text/parfmt.py,sha256=5TYCf-QfcwlECXUkrLSYFfewFA1JieKGTtm3X01fu64,12221
87
+ docx/oxml/text/parfmt.py,sha256=4JtA_Nvy9gx_6YusznQIxnkyiKmjL1KhmY3IqzORlsI,12767
88
88
  docx/oxml/text/run.py,sha256=pz8GAWT0uUq-V70fxFGKt1Q64zHGQW_d59GjyXfc4cA,11275
89
89
  docx/parts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
90
90
  docx/parts/comments.py,sha256=Dmxh_i8ADRo-wLfO9LV0Lyho5XC_76oU1NJN8itw8lc,1760
@@ -132,17 +132,17 @@ docx/text/font.py,sha256=AJI05dO5nUSXsutxHNsquZkqdCA33x68ovi3IV4C1nc,14854
132
132
  docx/text/hyperlink.py,sha256=bWU9yHEDrHK5Vngj35EuSJkANd593-6LgJji1Vo6FTo,5258
133
133
  docx/text/pagebreak.py,sha256=sI1yMVotkBtn1u5DJ9L04FkC01QoAwcyVSdgGPAkJIY,4950
134
134
  docx/text/paragraph.py,sha256=5caYCpNr9D-6pnk0aE5_HBkx5Bkc3VUWaj6u115Z9i8,6829
135
- docx/text/parfmt.py,sha256=70M75HFo7ydpqmIdZjkV711muyrsBGdr4WZscF3YVJY,10339
135
+ docx/text/parfmt.py,sha256=PHv4-k1zAd1kFGXAFlDn4Sl4K5kJQ8Pz9F9M-TVmfhA,10419
136
136
  docx/text/run.py,sha256=QtIRn3mW_MMLgbRIfJhRmnKpDfcq7VnJEQKn1pfsY78,10802
137
137
  docx/text/tabstops.py,sha256=bJN98GWW22f4Sqg0dQbyUcnuOn65fHsNZuCGswI03_c,3896
138
138
  docx/transforms/__init__.py,sha256=_hwIWF2o_Q2SA3GSyjRtObgOlComR36qNdDAsv18nIg,426
139
- docx/transforms/hyperlinks.py,sha256=a0PwM16c26Y1L6w_UdWDuZgGP4AbVg810ssoTjyMpTI,15746
139
+ docx/transforms/hyperlinks.py,sha256=onLHvZwi0ms0YG-WwaEfvkHzbUibtFZfLoTmVhuwXrc,16200
140
140
  docx/transforms/normalize.py,sha256=zfTU6aCZGmdhB1bnK-njhgPQPYmFVdN8KKhQ5VbT3QQ,4012
141
141
  docx/transforms/package.py,sha256=QFNG0vfqVCr8itO7la4IfSY8rDS5A1cMnYNgMT7SKag,3637
142
142
  docx/transforms/repair.py,sha256=ajBgbi7OtET-wugWw315OrLsFrY0z7_rocJWNHPtGas,1989
143
143
  docx/transforms/result.py,sha256=vteKga-spWOMW0blpoF9tER4vb5tdZH_iXmN61vB-0c,1058
144
- python_docx_oss-0.5.0.dist-info/licenses/LICENSE,sha256=lf2yZv-riPwFeah3IMDeG0zqI6fXcV9T9YOToeG54NM,1164
145
- python_docx_oss-0.5.0.dist-info/METADATA,sha256=Eyiy7maEsZPi4jIt3Fy_eIwZt4H8buqKEkgtPUeNjjs,9902
146
- python_docx_oss-0.5.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
147
- python_docx_oss-0.5.0.dist-info/top_level.txt,sha256=zkbrD3gmyqHpD_XhHe7lCbr2M5vT229nJ4UFqF5VjIs,5
148
- python_docx_oss-0.5.0.dist-info/RECORD,,
144
+ python_docx_oss-0.5.2.dist-info/licenses/LICENSE,sha256=lf2yZv-riPwFeah3IMDeG0zqI6fXcV9T9YOToeG54NM,1164
145
+ python_docx_oss-0.5.2.dist-info/METADATA,sha256=Bvx2Pwwcky5YfwUeUKHS-EZ3Dk8X1qeItUHpgs2YXC8,6769
146
+ python_docx_oss-0.5.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
147
+ python_docx_oss-0.5.2.dist-info/top_level.txt,sha256=zkbrD3gmyqHpD_XhHe7lCbr2M5vT229nJ4UFqF5VjIs,5
148
+ python_docx_oss-0.5.2.dist-info/RECORD,,
@@ -1,263 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: python-docx-oss
3
- Version: 0.5.0
4
- Summary: Create, read, and update Microsoft Word .docx files.
5
- Author: Ethan St Lee
6
- License-Expression: MIT
7
- Project-URL: Changelog, https://github.com/lsaint/python-docx-oss/blob/master/HISTORY.md
8
- Project-URL: Documentation, https://python-docx-oss.readthedocs.io/en/latest/
9
- Project-URL: Issues, https://github.com/lsaint/python-docx-oss/issues
10
- Project-URL: Repository, https://github.com/lsaint/python-docx-oss
11
- Keywords: docx,office,openxml,word
12
- Classifier: Development Status :: 5 - Production/Stable
13
- Classifier: Environment :: Console
14
- Classifier: Intended Audience :: Developers
15
- Classifier: Operating System :: OS Independent
16
- Classifier: Programming Language :: Python
17
- Classifier: Programming Language :: Python :: 3
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Programming Language :: Python :: 3.13
20
- Classifier: Programming Language :: Python :: 3.14
21
- Classifier: Topic :: Office/Business :: Office Suites
22
- Classifier: Topic :: Software Development :: Libraries
23
- Requires-Python: >=3.12
24
- Description-Content-Type: text/markdown
25
- License-File: LICENSE
26
- Requires-Dist: lxml>=6.1.0
27
- Requires-Dist: typing_extensions>=4.9.0
28
- Dynamic: license-file
29
-
30
- <p align="center">
31
- <img src="https://raw.githubusercontent.com/lsaint/python-docx-oss/master/docs/_static/img/oss.png" width="400" alt="python-docx-oss"/>
32
- </p>
33
-
34
- <p align="center">
35
- <strong>A Python SDK for advanced creation and manipulation of Microsoft Word <code>.docx</code> files.</strong>
36
- </p>
37
-
38
- <p align="center">
39
- <a href="https://pypi.org/project/python-docx-oss/"><img alt="PyPI" src="https://img.shields.io/pypi/v/python-docx-oss"></a>
40
- <a href="https://pypi.org/project/python-docx-oss/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/python-docx-oss.svg"></a>
41
- <a href="https://github.com/astral-sh/ruff"><img alt="Code style: Ruff" src="https://img.shields.io/badge/code%20style-ruff-FF6B6B.svg?logo=ruff&logoColor=white"></a>
42
- <a href="https://github.com/lsaint/python-docx-oss/blob/master/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a>
43
- </p>
44
-
45
- ## Overview
46
-
47
- `python-docx-oss` is an independently evolving DOCX SDK built on the proven API
48
- foundation of [`python-docx`](https://github.com/python-openxml/python-docx). It keeps
49
- the familiar `docx` programming model while extending it for advanced OOXML and Open
50
- Packaging Convention (OPC) workflows.
51
-
52
- Use it when an application needs more than basic paragraphs and tables: custom document
53
- metadata, application-owned XML, vector images, floating pictures, East Asian fonts,
54
- or low-level package and relationship access.
55
-
56
- ## Capability Matrix
57
-
58
- | Capability | Status | Primary API |
59
- | --- | --- | --- |
60
- | Documents, paragraphs, tables, styles, sections, headers, and footers | Stable | `Document()` and document object APIs |
61
- | Custom document properties | Stable | `document.custom_properties` |
62
- | Custom XML lifecycle | Stable | `add_custom_xml_part()`, `delete_custom_xml_part()` |
63
- | SVG and EMF images | Stable | `add_picture()` |
64
- | Inline and floating pictures | Stable | `add_picture()`, `add_float_picture()` |
65
- | Latin and East Asian font controls | Stable | `run.font.name`, `run.font.hAnsi`, `run.font.eastAsia` |
66
- | Low-level OPC parts and relationships | Stable | `document.part.package`, `part.rels` |
67
- | In-memory read, export, and independent copies | Stable | `Document()`, `to_bytes()`, `copy()` |
68
- | Document sanitization | Development | `document.sanitize()` |
69
- | Read-only package inspection and story feature scanning | Development | `inspect()` |
70
- | Configurable package-content fingerprints | Development | `fingerprint()`, `FingerprintPolicy` |
71
- | Explicit empty Custom XML repair and hyperlink normalization | Development | `repair()`, `normalize()` |
72
- | Package and semantic diff | Planned | — |
73
-
74
- ## Installation
75
-
76
- ```bash
77
- python -m pip install python-docx-oss
78
- ```
79
-
80
- The distribution name is `python-docx-oss`, but the Python import namespace remains
81
- `docx`:
82
-
83
- ```python
84
- from docx import Document
85
- ```
86
-
87
- > [!WARNING]
88
- > `python-docx` and `python-docx-oss` provide the same `docx` import namespace. Do not
89
- > install both distributions in the same Python environment.
90
-
91
- `python-docx-oss` currently supports Python 3.12, 3.13, and 3.14.
92
-
93
- ## Quick Start
94
-
95
- Create a document entirely in memory:
96
-
97
- ```python
98
- from io import BytesIO
99
-
100
- from docx import Document
101
-
102
- document = Document()
103
- document.add_heading("Quarterly Report", level=1)
104
- document.add_paragraph("Generated entirely in memory.")
105
-
106
- output = BytesIO()
107
- document.save(output)
108
-
109
- docx_bytes = output.getvalue()
110
- ```
111
-
112
- The same APIs also accept filesystem paths:
113
-
114
- ```python
115
- document = Document("input.docx")
116
- document.add_paragraph("Appended by python-docx-oss.")
117
- document.save("output.docx")
118
- ```
119
-
120
- ## Advanced Capabilities
121
-
122
- ### Package inspection and fingerprints
123
-
124
- Inspect damaged documents before opening them, without loading media payloads:
125
-
126
- ```python
127
- from docx import FingerprintPolicy, fingerprint, inspect
128
-
129
- report = inspect("input.docx")
130
- for finding in report.findings:
131
- print(finding.code, finding.partname)
132
-
133
- digest = fingerprint("input.docx", policy=FingerprintPolicy(exclude_parts=("docProps/*",)))
134
- ```
135
-
136
- These APIs leave inputs unchanged and restore seekable stream positions. Fingerprints
137
- ignore ZIP metadata and member ordering; all content is included unless explicitly
138
- excluded. See [Package inspection and fingerprints](docs/user/inspection.rst) for
139
- finding codes, XML comparison semantics, and policy rules.
140
-
141
- ### Explicit repair and normalization
142
-
143
- ```python
144
- from docx import normalize, repair
145
-
146
- repaired = repair(source_bytes, empty_custom_xml=True)
147
- if repaired.report.succeeded:
148
- normalized = normalize(repaired.content, hyperlink_fields=True, hyperlink_runs=True)
149
- if normalized.report.succeeded:
150
- output_bytes = normalized.content
151
- ```
152
-
153
- Operations are disabled by default. Results include committed changes, skipped cases,
154
- and errors; validation failures return the original bytes. See
155
- [Repair and normalization](docs/user/transformations.rst) for supported structures,
156
- selection callbacks, and preservation rules.
157
-
158
- ### Custom properties
159
-
160
- ```python
161
- document = Document()
162
- document.custom_properties["workflow_status"] = "approved"
163
- document.custom_properties["revision"] = 3
164
- ```
165
-
166
- Custom properties are visible in Microsoft Word and stored in
167
- `/docProps/custom.xml`. See [Working with custom
168
- properties](docs/user/custom-properties.rst).
169
-
170
- ### Custom XML
171
-
172
- ```python
173
- custom_xml = document.part.add_custom_xml_part(
174
- '<order xmlns="urn:example:orders" id="A-001"/>',
175
- )
176
- custom_xml.add_item("status", "ready")
177
- ```
178
-
179
- See [Working with Custom XML](docs/user/custom-xml.rst) for lifecycle and compatibility
180
- considerations.
181
-
182
- ### East Asian fonts
183
-
184
- ```python
185
- run = document.add_paragraph().add_run("English 与中文")
186
- run.font.name = "Open Sans"
187
- run.font.eastAsia = "Microsoft YaHei"
188
- ```
189
-
190
- SVG and EMF streams can be passed to the standard picture APIs. Floating pictures are
191
- available through `Document.add_float_picture()` and `Run.add_float_picture()`.
192
-
193
- ## Compatibility and Scope
194
-
195
- - The project maintains broad compatibility with the public `python-docx` API while
196
- following its own versioning and product roadmap.
197
- - Clean lxml integration: Low-level OXML elements avoid shadowing lxml's Cython
198
- `_Element.text` descriptor (using `.texts` internally). This guarantees that standard
199
- `element.itertext()` on parent elements and untyped revision nodes (`w:ins`, `w:del`,
200
- `w:txbxContent`) never duplicates text, while high-level proxy APIs (`paragraph.text`,
201
- `run.text`) remain fully compatible with `python-docx`.
202
- - Compatibility does not extend to every private or internal `python-docx` API. Test
203
- those integrations before migrating production systems.
204
- - The SDK focuses exclusively on DOCX. It is not a general XLSX/PPTX Office suite.
205
- - It edits document structure but does not implement Word's page-layout rendering
206
- engine.
207
- - CLI, MCP, web, desktop, and Agent runtimes belong in separate packages that consume
208
- this SDK.
209
-
210
- ## Documentation
211
-
212
- - [Documentation site](https://python-docx-oss.readthedocs.io/en/latest/)
213
- - [Installation guide](docs/user/install.rst)
214
- - [Quickstart](docs/user/quickstart.rst)
215
- - [User guide](docs/index.rst)
216
- - [API reference](docs/index.rst#api-documentation)
217
- - [Custom properties](docs/user/custom-properties.rst)
218
- - [Custom XML](docs/user/custom-xml.rst)
219
- - [python-docx compatibility](docs/user/compatibility.rst)
220
- - [Upstream maintenance](docs/dev/upstream-maintenance.rst)
221
- - [Release history](HISTORY.md)
222
-
223
- ## Quality and Testing
224
-
225
- The test suite combines unit and acceptance coverage with in-memory round-trip tests
226
- using documents created by Microsoft Word. The integration fixtures cover floating
227
- pictures, SVG fallback relationships, East Asian fonts, Custom XML parts, and core OPC
228
- package preservation.
229
-
230
- For local development:
231
-
232
- ```bash
233
- uv sync
234
- uv run pytest
235
- uv run ruff check .
236
- uv run pyright
237
- ```
238
-
239
- ## Project Status
240
-
241
- The current focus is stabilizing the independent SDK baseline, its in-memory workflows,
242
- sanitization, and read-only package analysis before expanding document comparison,
243
- composition, and validation APIs.
244
-
245
- ## Credits
246
-
247
- This project builds on the original work of
248
- [`python-docx`](https://github.com/python-openxml/python-docx) creator Steve Canny and
249
- its contributors. `python-docx-oss` is maintained by Ethan St Lee and its contributors.
250
-
251
- ## Why “OSS”?
252
-
253
- In Brazilian jiu-jitsu, “oss” is a greeting and an expression of respect. It reflects
254
- the same spirit of discipline and collaboration behind this project.
255
-
256
- ## License
257
-
258
- `python-docx-oss` is released under the [MIT License](LICENSE).
259
-
260
- ## Support
261
-
262
- If this project is useful to you, you can support its continued development through
263
- the [donation page](https://lsaint.github.io/donation/?utm_source=github&utm_medium=readme&utm_campaign=python-docx-oss).