forked from python-openxml/python-docx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
57 lines (46 loc) · 1.62 KB
/
api.py
File metadata and controls
57 lines (46 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# encoding: utf-8
"""
Directly exposed API functions and classes, :func:`Document` for now.
Provides a syntactically more convenient API for interacting with the
OpcPackage graph.
"""
import os
from docx.opc.package import OpcPackage
from docx.opc.constants import CONTENT_TYPE as CT
thisdir = os.path.split(__file__)[0]
_default_docx_path = os.path.join(thisdir, 'templates', 'default.docx')
def Document(docx=None):
"""
Return a |_Document| instance loaded from *docx*, where *docx* can be
either a path to a ``.docx`` file (a string) or a file-like object. If
*docx* is missing or ``None``, the built-in default document "template"
is loaded.
"""
if docx is None:
docx = _default_docx_path
pkg = OpcPackage.open(docx)
document_part = pkg.main_document
if document_part.content_type != CT.WML_DOCUMENT_MAIN:
tmpl = "file '%s' is not a Word file, content type is '%s'"
raise ValueError(tmpl % (docx, document_part.content_type))
return _Document(pkg, document_part)
class _Document(object):
"""
API class representing a Word document.
"""
def __init__(self, pkg, document_part):
super(_Document, self).__init__()
self._document = document_part
self._pkg = pkg
@property
def body(self):
"""
Return a reference to the |_Body| instance for this document.
"""
return self._document.body
def save(self, file_):
"""
Save this document to *file_*, where *file_* can be either a path to
a file (a string) or a file-like object.
"""
return self._pkg.save(file_)