Skip to content

Commit ebd8d62

Browse files
committed
feat: add save_to_word function for exporting images to Word documents
1 parent bd319cf commit ebd8d62

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

pydelmod/plotutils.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from xml.dom.minidom import Document
12
import pandas as pd
23
import numpy as np
34
import hvplot.pandas
@@ -82,3 +83,51 @@ def exceedance_plot(
8283

8384
def save_figure(fig, filename):
8485
fig.savefig(filename, dpi=300, bbox_inches="tight")
86+
87+
88+
#
89+
import pathlib
90+
91+
92+
def save_to_word(
93+
word_file, image_file, image_alt_text=None, image_caption=None, image_width=6.0
94+
):
95+
"""
96+
Save an image to a Word document with metadata.
97+
98+
word_file: The path to the Word document. If it exists, the image will be added to it, else a new one will be created.
99+
image_file: The path to the image file.
100+
image_alt_text: Alternative text for the image.
101+
image_caption: Caption for the image.
102+
image_width: Width of the image in inches.
103+
104+
Note: requires pip install python-docx
105+
"""
106+
try:
107+
from pydoc import doc
108+
from docx import Document
109+
from docx.shared import Inches
110+
from docx.oxml.shared import OxmlElement, qn
111+
except ImportError:
112+
print("Error: Required modules are not installed.")
113+
print("pip install python-docx")
114+
return
115+
if not pathlib.Path(word_file).exists():
116+
doc = Document()
117+
else:
118+
doc = Document(word_file)
119+
120+
p = doc.add_paragraph()
121+
run = p.add_run()
122+
picture = run.add_picture(image_file, width=Inches(image_width))
123+
# Add alt text (good for accessibility/search inside Word)
124+
# (python-docx doesn’t expose alt text directly; set it via XML on the inline drawing)
125+
if image_alt_text:
126+
inline = picture._inline
127+
docPr = inline.docPr
128+
docPr.set("title", image_caption)
129+
docPr.set("descr", image_alt_text)
130+
if image_caption:
131+
caption = doc.add_paragraph(image_caption)
132+
doc.add_page_break()
133+
doc.save(word_file)

0 commit comments

Comments
 (0)