How to programmatically open and modify ODT file from Calc Macro

2.5k Views Asked by At

I am writing a Macro programm in a LibreOffice Calc spreadsheet. This macro should do the following (amongst other things):

  • open an existing ODT text document as a template
  • search and replace some strings with new values
  • save a copy of this as a new file
  • generate and open a PDF version

Is this possible somehow using LibreOffice Basic only? I have found nothing in the Libreoffice docs and examples and only this slightly related answer here on SO: How to programatically modify Open/Libre Office odt document? Thanks!

1

There are 1 best solutions below

2
On BEST ANSWER

open an existing ODT text document as a template

The method to open a document is loadComponentFromURL, for example https://help.libreoffice.org/6.4/en-US/text/sbasic/shared/stardesktop.html. There is nothing especially difficult about opening a document in Writer from a Calc macro, as LibreOffice components are well integrated. Remember to use the object returned from opening the document instead of ThisComponent.

search and replace some strings with new values

Andrew's Macro Document section 7.14. Search And Replace shows some ways to do this.

save a copy of this as a new file

The command is storeAsURL which is like "save as", not to be confused with storeToURL which would modify the existing file. See https://wiki.openoffice.org/wiki/Saving_a_document.

generate and open a PDF version

Generating a PDF is like any other save. The only difference is that the export filter writer_pdf_Export must be specified. An example is at https://ask.libreoffice.org/en/question/178818/how-i-export-pdf-using-macro/.

As for opening the PDF, what application do you want to open it? LibreOffice Draw can open a PDF although it's not a normal PDF viewer. Shell can call the viewer of your choice.