Hiya!
i am trying to use scriptforge and python to open a writer document,
replace some standin words and saves the file as something else
I am having trouble having spent days with this, so far it just saves the file but doesnt replace anything.
see my code below:
import os
import subprocess
import uno
from scriptforge import ScriptForge, CreateScriptService
# Initialize ScriptForge with default settings
ScriptForge(hostname='localhost', port=2021)
# open template and soffice --writer --accept='socket,host=localhost,port=2021;urp;
def is_libreoffice_running():
"""
Check if LibreOffice is running on the system.
"""
try:
if os.name == 'nt':
output = subprocess.check_output('tasklist', shell=True)
return b'soffice.bin' in output
except Exception as e:
print(f"Error checking LibreOffice status: {e}")
return False
def process_template():
"""
Process the template by replacing placeholders with actual values.
"""
# Define template and output paths
template_path = r"C:\Print_Webpage\RecommendedFruitingDateLabel.odt" #
output_path = r"C:\Print_Webpage\Output.odt" # Adjust this path as needed
# Check if the template file exists
if not os.path.exists(template_path):
print(f"Error: The file does not exist at the specified path: {template_path}")
return
print("Starting process_template...")
try:
# Log the attempt to create a script service
print(f"Attempting to create Document service with template path: {template_path}")
doc = CreateScriptService("Document", template_path)
if doc is None:
print("Failed to create Document service. Please check if the template is valid and LibreOffice is running.")
return
print("Services initialized successfully.")
except Exception as e:
print(f"Error initializing services: {e}") # Log the error
return
# Define replacements for fields
replacements = {
"<Species>": "Pink Oyster",
"<RFD>": "10",
"<TU>": "Days"
}
# Iterate through replacements and apply them
for field, replacement in replacements.items():
try:
doc.RunCommand("SelectData")
doc.RunCommand(".uno:ReplaceAll", field, replacement)
print(f"replacing '{field}': with {replacement}") # Output any errors
except Exception as e:
print(f"Error replacing '{field}': {e}") # Output any errors
# Save the modified document
#doc.Save
doc.SaveAs(output_path, overwrite=True)
print("Template processed and saved successfully.")
# ...
if __name__ == "__main__":
if not is_libreoffice_running():
print("LibreOffice is not running. Please start LibreOffice and try again.")
else:
process_template() # Call the function to process the template