Skip to content

pkgwriter

pkgwriter

Provides low-level, write-only API to serialized (OPC) package.

OPC stands for Open Packaging Convention. This is e, essentially an implementation of OpcPackage.save().

PackageWriter

Writes a zip-format OPC package to pkg_file, where pkg_file can be either a path to a zip file (a string) or a file-like object.

Its single API method, write, is static, so this class is not intended to be instantiated.

write staticmethod

write(pkg_file, pkg_rels, parts)

Write a physical package (.pptx file) to pkg_file containing pkg_rels and parts and a content types stream based on the content types of the parts.

Source code in src/docx/opc/pkgwriter.py
@staticmethod
def write(pkg_file, pkg_rels, parts):
    """Write a physical package (.pptx file) to `pkg_file` containing `pkg_rels` and
    `parts` and a content types stream based on the content types of the parts."""
    phys_writer = PhysPkgWriter(pkg_file)
    # -- parts arrive in graph-traversal order, which varies between runs. Sort
    # -- them so the same document always serializes to the same bytes. --
    sorted_parts = sorted(parts, key=lambda part: part.partname)
    PackageWriter._write_content_types_stream(phys_writer, sorted_parts)
    PackageWriter._write_pkg_rels(phys_writer, pkg_rels)
    PackageWriter._write_parts(phys_writer, sorted_parts)
    phys_writer.close()

_ContentTypesItem

_ContentTypesItem()

Service class that composes a content types item ([Content_Types].xml) based on a list of parts.

Not meant to be instantiated directly, its single interface method is xml_for(), e.g. _ContentTypesItem.xml_for(parts).

Source code in src/docx/opc/pkgwriter.py
def __init__(self):
    self._defaults = CaseInsensitiveDict()
    self._overrides = {}

blob property

blob

Return XML form of this content types item, suitable for storage as [Content_Types].xml in an OPC package.

from_parts classmethod

from_parts(parts)

Return content types XML mapping each part in parts to the appropriate content type and suitable for storage as [Content_Types].xml in an OPC package.

Source code in src/docx/opc/pkgwriter.py
@classmethod
def from_parts(cls, parts):
    """Return content types XML mapping each part in `parts` to the appropriate
    content type and suitable for storage as ``[Content_Types].xml`` in an OPC
    package."""
    cti = cls()
    cti._defaults["rels"] = CT.OPC_RELATIONSHIPS
    cti._defaults["xml"] = CT.XML
    for part in parts:
        cti._add_content_type(part.partname, part.content_type)
    return cti