Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for docx export #18

Open
ldallolio opened this issue Mar 6, 2024 · 0 comments
Open

Support for docx export #18

ldallolio opened this issue Mar 6, 2024 · 0 comments

Comments

@ldallolio
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant