Skip to content

Support for docx export #18

@ldallolio

Description

@ldallolio

Hi,
Thank you for this port, it really helped me!
I had to embed a Quill diff into a MS Word document, I would like to share some lines in case you want to add this export format :


from docx import Document
from delta import Delta
import io, base64

doc = Document()
for delta, attrs, index in Delta(test_ops).iter_lines():
    p = doc.add_paragraph()
    for op in delta.ops:
        insert_value = op.get('insert')
        attributes = op.get('attributes', {})
        if isinstance(insert_value, str) and insert_value:
            text = insert_value
            if 'header' in attrs:
                doc.add_heading(text, level=attrs['header'])
                continue
            if 'list' in attrs:
                list_style = 'List Number' if attrs['list'] == 'ordered' else 'List Bullet'
                if 'indent' in attrs:
                    list_style += f" {int(attrs['indent']) + 1}" 
                p.style = list_style
            run = p.add_run(text)
            if 'script' in attributes:
                if attributes['script'] == 'sub':
                    run.subscript = True
                if attributes['script'] == 'super':
                    run.superscript = True
            run.strike = attributes.get('strike', False)
            run.bold = attributes.get('bold', False) or attributes.get('strong', False)
            run.italic = attributes.get('italic', False) or attributes.get('em', False)
            run.underline = attributes.get('underline', False)
        elif isinstance(insert_value, dict):
            if 'image' in insert_value:
                image_content = insert_value["image"]
                prefix = "data:image/png;base64,"
                if image_content.startswith(prefix):
                    image_bytes = base64.b64decode(image_content[len(prefix):])
                image_stream = io.BytesIO(image_bytes)
                doc.add_picture(image_stream)

Here it is, nothing really complicated indeed :-) If you are interested, I could try to write something similar to the html exporter, just let me know ;)

All the best

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions