Skip to content

Instantly share code, notes, and snippets.

@shantanuo
Created September 27, 2024 09:55
Show Gist options
  • Save shantanuo/f635bbdb764d1fafa8587203d7f8823a to your computer and use it in GitHub Desktop.
Save shantanuo/f635bbdb764d1fafa8587203d7f8823a to your computer and use it in GitHub Desktop.
import uno
import argparse
from com.sun.star.beans import PropertyValue
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
def replace_newline(document):
search = document.createSearchDescriptor()
search.SearchString = '\\n'
search.SearchRegularExpression = True
search.ReplaceString = '\\n'
document.replaceAll(search)
def create_file_from_template(template_path, output_path, text_content):
# Set up the connection to LibreOffice
local_context = uno.getComponentContext()
resolver = local_context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local_context)
context = resolver.resolve("uno:pipe,name=libreoffice;urp;StarOffice.ComponentContext")
desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
# Load the template
template_url = uno.systemPathToFileUrl(template_path)
document = desktop.loadComponentFromURL(template_url, "_blank", 0, ())
text = document.Text
cursor = text.createTextCursor()
text.insertString(cursor, text_content.getString(), False)
text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
output_url = uno.systemPathToFileUrl(output_path)
replace_newline(document)
pdf_export = (
PropertyValue("FilterName", 0, "writer_pdf_Export", 0),
)
output_url = uno.systemPathToFileUrl("/workspace/output.pdf")
document.storeToURL(output_url, pdf_export)
document.dispose()
def apply_template_and_convert_to_pdf(document_path, template_path):
# Create the LibreOffice UNO connection
local_context = uno.getComponentContext()
resolver = local_context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local_context)
# Connect to LibreOffice
context = resolver.resolve("uno:pipe,name=libreoffice;urp;StarOffice.ComponentContext")
desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
# Load the document
document_url = uno.systemPathToFileUrl(document_path)
document = desktop.loadComponentFromURL(document_url, "_blank", 0, ())
x = document.getText()
create_file_from_template(template_path, '/workspace/output.odt', x)
# Close the document
document.dispose()
if __name__ == "__main__":
# Define command-line arguments
parser = argparse.ArgumentParser(description="Apply template and convert to PDF")
parser.add_argument("document", help="Path to the input document (.odt)")
parser.add_argument("template", help="Path to the template (.ott)")
# Parse the arguments
args = parser.parse_args()
# Call the function with the provided arguments
apply_template_and_convert_to_pdf(args.document, args.template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment