I have this code that trying to generate a word document. I have the document working except the image adding. When I try to add a run, the image doesn't show up. When I try to add a picture to the document, it adds it to the end of the document, not in the body of the document. I am trying to debug by doing it for every paragraph. My template only has 3 paragraphs and a table as of right now. There are no errors showing in my console
from docx import Document
from docx.shared import Inches, RGBColor
from docx2pdf import convert
from PIL import Image
import re
import os
from io import BytesIO
import requests
from docx.enum.text import WD_ALIGN_PARAGRAPH # Import for alignment
def process_docx(docx_path, data, output_format):
try:
doc = Document(docx_path)
except FileNotFoundError:
print(f"Error: Could not find docx file at {docx_path}")
return None
for table in doc.tables:
for row in list(table.rows): # Iterate over a copy to avoid issues while modifying
if "{start." in row.cells[0].text: # Check the first cell for the start tag
start_tag = row.cells[0].text
match = re.search(r"{start\.(\w+)}", start_tag)
if match:
data_key = match.group(1)
if data_key in data['data'] and isinstance(data['data'][data_key], list):
# Store the template row content for later use.
template_row_cells = [cell.text for cell in row.cells]
# Remove the original row *before* processing items
table._element.remove(row._element)
for item in data['data'][data_key]:
new_row = table.add_row().cells
for i, cell_text in enumerate(template_row_cells):
field_match = re.search(r"{" + data_key + "\.(\w+)}", cell_text)
if field_match:
field_name = field_match.group(1)
new_row[i].text = item.get(field_name, "")
else:
new_row[i].text = cell_text # Keep other text
else: # process paragraph if no start tag in the first cell
for cell in row.cells:
for paragraph in cell.paragraphs:
process_paragraph(paragraph)
for paragraph in doc.paragraphs:
"""try:
img = Image.open(image_bytes) # Will raise PIL.UnidentifiedImageError if not an image
img.verify() # Further check image integrity
except Exception as e:
raise Exception(f"Invalid image format or corrupted image from URL: {e}")"""
run = paragraph.add_run()
run.add_picture('Image.png')
run.add_text('TESTING THIS')
process_paragraph(paragraph)
doc.add_picture('Image.png', width=Inches(1), height=Inches(1))
#...
The image(s) are not showing up in the body of the document. Let's say after paragraph 1, the image should show up in between paragraph 1 and 2, but it is not showing up.