import datetime
import logging
import win32com.client
from pathlib import Path
from constants import WordFilePath, Word_folder
# Configure logging
logging.basicConfig(
filename="word_handler.log", # Log file
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
class WordHandler:
def __init__(self, next_wir_number, rev):
self.next_wir_number = str(next_wir_number).zfill(5) # Format WIR No to 5
digits
self.rev = rev # Fixed capitalization for consistency
self.template_path = Path(WordFilePath)
self.save_folder = Path(Word_folder)
self.word_path = Path(WordFilePath)
self.save_folder.mkdir(parents=True, exist_ok=True) # Ensure directory
exists
def update_bookmarks(self, data):
word = win32com.client.Dispatch("Word.Application")
word.Visible = False # Run in the background
try:
# Open template
doc = word.Documents.Open(str(self.template_path))
# Define the bookmark values
bookmark_values = {
'WIRNo': f"{self.next_wir_number} - R {self.rev}", # Fixed en-dash
issue
'CreatedDate1': datetime.date.today().strftime('%d %b %Y'),
'CreatedDate2': datetime.date.today().strftime('%d %b %Y'),
'CreatedDate3': datetime.date.today().strftime('%d %b %Y'),
'InspectionDate': data['Inspection_Date'].strftime('%d %b %Y'),
'PlotNo': data['villa'],
'Part': data['part'],
'Level': data['level'],
'Description': data['description'],
}
print(bookmark_values)
logging.info(f"Updating bookmarks with data: {bookmark_values}")
# Update bookmarks
for bookmark, value in bookmark_values.items():
if doc.Bookmarks.Exists(bookmark): # More efficient check
doc.Bookmarks(bookmark).Range.Text = str(value)
else:
logging.warning(f"Bookmark '{bookmark}' not found in the
template.")
# Define save path
save_path = self.save_folder / f"WIR-{self.next_wir_number}-
R{self.rev}.docx"
# Save as new Word file
doc.SaveAs2(str(save_path), FileFormat=16) # FileFormat=16 for DOCX
logging.info(f"Word file saved successfully: {save_path}")
except Exception as e:
logging.error(f"Error updating Word file: {e}")
print(f"Error updating Word file: {e}")
finally:
if 'doc' in locals(): # Ensure document is closed if opened
doc.Close()
word.Quit()