Exemplo n.º 1
0
 def test_with_bad_zip_file_raises_MalformedDocxException(self):
     archive = BytesIO(b'foo')
     try:
         with ZipFile(archive):
             pass
         raise AssertionError('Excepted MalformedDocxException')
     except MalformedDocxException:
         pass
Exemplo n.º 2
0
def get_image_data(docx_file_path, image_name):
    """
    Return base 64 encoded data for the image_name that is stored in the
    docx_file_path.
    """
    with ZipFile(docx_file_path) as f:
        images = [
            e for e in f.infolist()
            if e.filename == 'word/media/%s' % image_name
        ]
        if not images:
            raise AssertionError('%s not in %s' % (image_name, docx_file_path))
        data = f.read(images[0].filename)
    return base64.b64encode(data).decode()
Exemplo n.º 3
0
    def build_and_convert_document_to_html(
        self,
        body=None,
        style=None,
        numbering=None,
        word_relationships=None,
    ):
        default_word_relationships = '''
          <Relationship Id="rId1" Type="{styles_rel_type}"
            Target="styles.xml"/>
          <Relationship Id="rId2" Type="{numbering_rel_type}"
            Target="numbering.xml"/>
        '''.format(
            styles_rel_type=StyleDefinitionsPart.relationship_type,
            numbering_rel_type=NumberingDefinitionsPart.relationship_type,
        )

        if word_relationships is None:
            word_relationships = default_word_relationships

        if word_relationships:
            word_relationships = self.wrap_relationship_xml(word_relationships)

        if body:
            body = self.wrap_body_xml(body)

        if style:
            style = self.wrap_style_xml(style)

        if numbering:
            numbering = self.wrap_numbering_xml(numbering)

        document = {
            '_rels/.rels': self.base_relationships,
            'word/_rels/document.xml.rels': word_relationships,
            'word/document.xml': body,
            'word/styles.xml': style,
            'word/numbering.xml': numbering,
            '[Content_Types].xml': self.content_types,
        }

        zip_file = tempfile.NamedTemporaryFile()
        with ZipFile(zip_file.name, 'w') as zf:
            for arcname, data in document.items():
                if data is None:
                    continue
                zf.writestr(arcname, data)

        yield zip_file.name