Servicio SFDocuments.Document

The SFDocuments library provides methods and properties to facilitate the management and manipulation of LibreOffice documents.

Methods that are applicable for all types of documents (Text Documents, Sheets, Presentations, etc) are provided by the SFDocuments.Document service. Some examples are:

warning

Las propiedades, los métodos y los argumentos que se señalan con un (*) NO son aplicables a los documentos de Base.


Methods and properties that are specific to certain LibreOffice components are stored in separate services, such as SFDocuments.SF_Calc and SFDocuments.SF_Base.

Although the Basic language does not offer inheritance between object classes, the latter services may be considered as subclasses of the SFDocuments.Document service. Such subclasses can invoke the properties and methods described below.

Invocación del servicio

Below are three variants of how the Document service can be invoked.

In Basic

Using the getDocument method from the ScriptForge.UI service:


    Dim ui As Object, oDoc As Object
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.GetDocument("Untitled 1")
  

Alternatively you can use the methods CreateDocument and OpenDocument from the UI service.


    Set oDocA = ui.CreateDocument("Calc")
    Set oDocB = ui.OpenDocument("C:\Documents\MyFile.odt")
  

Directamente, si el documento ya está abierto.


    Dim oDoc As Object
    Set oDoc = CreateScriptService("SFDocuments.Document", "Untitled 1") 'Default = ActiveWindow
  

A partir de una macro desencadenada por un suceso del documento.


    Sub RunEvent(ByRef poEvent As Object)
        Dim oDoc As Object
        Set oDoc = CreateScriptService("SFDocuments.DocumentEvent", poEvent)
        ' (...)
    End Sub
  
note

The Document service is closely related to the UI and FileSystem services.


Except when the document was closed by program with the CloseDocument method (it is then superfluous), it is recommended to free resources after use:


    Set oDoc = oDoc.Dispose()
  
In Python

    from scriptforge import CreateScriptService
    ui = CreateScriptService("UI")
    doc = ui.GetDocument("Untitled 1")
    # (...)
    doc.Dispose()
  

    docA = ui.CreateDocument("Calc")
    docB = ui.OpenDocument("C:\Documents\MyFile.odt")
  

    doc = CreateScriptService("SFDocuments.Document", "Untitled 1")
  

    def RunEvent(event)
        doc = CreateScriptService("SFDocuments.DocumentEvent", Event)
        # (...)
  
tip

El uso del prefijo «SFDocuments.» al llamar el servicio es facultativo.


Propiedades

Nombre

De solo lectura

Tipo

Descripción

CustomProperties (*)

No

Dictionary service

Returns a ScriptForge.Dictionary object instance. After update, can be passed again to the property for updating the document.
Individual items of the dictionary may be either strings, numbers, (Basic) dates or com.sun.star.util.Duration items.

Description (*)

No

String

Da acceso a la propiedad Description del documento (conocida también como «Comments»)

DocumentProperties (*)

Dictionary service

Devuelve un objeto ScriptForge.Dictionary que contiene todas las entradas. Las estadísticas del documento también se incluyen. Observe que los elementos del diccionario dependen del tipo de documento. Por ejemplo, un documento de Calc incluye una entrada «CellCount», mientras que otros tipos de documento no tienen esa entrada.

DocumentType

String

Valor de cadena con el tipo de documento («Base», «Calc», «Writer», etc.)

IsBase
IsCalc
IsDraw
IsImpress
IsMath
IsWriter

Boolean

Exactly one of these properties is True for a given document.

Keywords (*)

No

String

Da acceso a la propiedad Keywords del documento. Se representa como una lista de palabras clave separadas por comas

Readonly (*)

Boolean

True si el documento está en el modo de solo lectura

Subject (*)

No

String

Da acceso a la propiedad Subject del documento.

Title (*)

No

String

Da acceso a la propiedad Title del documento.

XComponent

Objeto de UNO

The UNO object com.sun.star.lang.XComponent or com.sun.star.comp.dba.ODatabaseDocument representing the document


Ejemplo:

In Basic

The example below prints all the properties of a document. Note that the oDoc object returned by the UI.OpenDocument method is a SFDocuments.Document object.


    Dim ui as Variant : Set ui = CreateScriptService("UI")
    Dim oDoc as Object
    Set oDoc = ui.OpenDocument("C:\Documents\MyFile.ods")
    Dim propDict as Object
    Set propDict = oDoc.DocumentProperties
    Dim keys as Variant : propKeys = propDict.Keys
    Dim k as String, strProp as String
    For Each k In propKeys
        strProp = strProp & k & ": " & propDict.Item(k) & CHR$(10)
    Next k
    MsgBox strProp
    oDoc.CloseDocument()
  
In Python

To access document properties in a Python script the user needs to directly access them using their names, as shown below:


    doc = ui.GetDocument(r"C:\Documents\MyFile.ods")
    msg = doc.Title + '\n' + doc.Description + '\n' + doc.Keywords
    bas = CreateScriptService("Basic")
    bas.MsgBox(msg)
    doc.CloseDocument()
  

Lista de métodos en el servicio Document

Activate
CloseDocument
Forms

RunCommand
Save

SaveAs
SaveCopyAs


Activate

Returns True if the document could be activated. Otherwise, there is no change in the actual user interface. It is equivalent to the Activate method of the UI service.

Este método es útil cuando se necesita dar el foco a un documento que está minimizado u oculto.

Sintaxis:

svc.Activate(): bool

Ejemplo:

The example below considers that the file "My_File.ods" is already open but not active.

In Basic

    Dim oDoc As Object
    Set oDoc = CreateScriptService("Document", "MyFile.ods")
    oDoc.Activate()
  
In Python

    doc = CreateScriptService("Document", "MyFile.ods")
    doc.Activate()
  
tip

Keep in mind that you can invoke the Document service by passing to CreateScriptService either "Document" or "SFDocuments.Document"


CloseDocument

Closes the document. If the document is already closed, regardless of how the document was closed, this method has no effect and returns False.

The method will also return False if the user declines to close it.

Returns True if the document was successfully closed.

Sintaxis:

svc.CloseDocument(saveask: bool = True): bool

Parámetros:

saveask : If True (default), the user is invited to confirm if the changes should be written on disk. This argument is ignored if the document was not modified.

Ejemplo:

In Basic

    If oDoc.CloseDocument(True) Then
        ' ...
    End If
  
In Python

    if doc.CloseDocument(True):
        # ...
  

Forms

En función de los parámetros provistos, este método devolverá:

note

This method is applicable only for Writer documents. Calc and Base documents have their own Forms method in the Calc and Base services, respectively.


Sintaxis:

svc.Forms(): str[0..*]

svc.Forms(form: str = ''): svc

svc.Forms(form: int): svc

Parámetros:

form: The name or index corresponding to a form stored in the document. If this argument is absent, the method will return a list with the names of all forms available in the document.

Ejemplo:

In the following examples, the first line gets the names of all forms in the document and the second line retrieves the Form object of the form named "Form_A".

In Basic

    Set FormNames = oDoc.Forms()
    Set FormA = oDoc.Forms("Form_A")
  
In Python

    form_names = doc.Forms()
    form_A = doc.Forms("Form_A")
  

RunCommand

Runs a command on a document. The command is executed without arguments.

A few typical commands are: Save, SaveAs, ExportToPDF, SetDocumentProperties, Undo, Copy, Paste, etc.

The document itself does not need to be active to be able to run commands.

Sintaxis:

svc.RunCommand(command: str)

Parámetros:

command: Case-sensitive string containing the command in English. The command itself is not checked for correctness. If nothing happens after the command call, then the command is probably wrong.

Ejemplo:

The following example runs the "SelectData" command in a Calc sheet named "MyFile.ods", which will result in the selection of the data area based on the currently selected cell.

In Basic

    Set oDoc = CreateScriptService("Document", "MyFile.ods")
    oDoc.RunCommand("SelectData")
  
In Python

    doc = CreateScriptService("Document", "MyFile.ods")
    doc.RunCommand("SelectData")
  

The example above actually runs the UNO command uno:SelectData. Hence, to use the RunCommand method it is necessary to remove the "uno:" substring.

tip

Each LibreOffice component has its own set of commands available. One easy way to learn commands is going to Tools > Customize > Keyboard. When you position your mouse over a function in the Function list, a tooltip will appear with the corresponding UNO command.


Save

Stores the document to the file location from which it was loaded. The method is ignored if the document was not modified.

Returns False if the document could not be saved. An error is raised if the file is open as read-only, or if it is a new file that has not been saved yet.

El documento en sí no necesita estar activo para ejecutar este método.

Sintaxis:

svc.Save(): bool

Ejemplo:

In Basic

    If Not oDoc.Save() Then
        ' ...
    End If
  
In Python

    if not doc.Save():
        # ...
  

SaveAs

Stores the document to the given file location. The new location becomes the new file name on which simple Save method calls will be applied.

Returns False if the document could not be saved. An error is raised when overwriting the destination is rejected or when the destination has its read-only attribute set.

El documento en sí no necesita estar activo para ejecutar este método.

Sintaxis:

svc.SaveAs(filename: str, overwrite: bool = False, password: str = '', filtername: str = '', filteroptions: str = ''): bool

Parámetros:

filename: A string containing the file name to be used. It must follow the SF_FileSystem.FileNaming notation.

overwrite: If True, the destination file may be overwritten (default = False).

password (*): A non-space string to protect the document.

filtername (*): The name of a filter that should be used for saving the document. If this argument is passed, then the filter must exist.

filteroptions (*): An optional string of options associated with the filter.

Ejemplo:

In Basic

    oDoc.SaveAs("C:\Documents\NewCopy.odt", overwrite := True)
  
In Python

    doc.SaveAs(r"C:\Documents\NewCopy.odt", overwrite = True)
  

SaveCopyAs

Almacena una copia de o exporta el documento en la ubicación de archivo que se indique. El archivo actual no se modifica.

Devuelve Falso si el documento no pudo guardarse. Se emite un error si se rechaza sobrescribir el archivo de destino o cuando el atributo «de solo lectura» está activo en el archivo de destino.

El documento en sí no necesita estar activo para ejecutar este método.

Sintaxis:

svc.SaveCopyAs(filename: str, overwrite: bool = False, password: str = '', filtername: str = '', filteroptions: str = ''): bool

Parámetros:

filename: A string containing the file name to be used. It must follow the SF_FileSystem.FileNaming notation.

overwrite: If True, the destination file may be overwritten (default = False).

password (*): A non-space string to protect the document.

filtername (*): The name of a filter that should be used for saving the document. If this argument is passed, then the filter must exist.

filteroptions (*): An optional string of options associated with the filter.

Ejemplo:

In Basic

    oDoc.SaveCopyAs("C:\Documents\Copy2.odt", Overwrite := True)
  
In Python

    doc.SaveCopyAs(r"C:\Documents\Copy2.odt", overwrite = True)
  
warning

Todas las rutinas o los identificadores Basic de ScriptForge que comienzan por un guion bajo «_» son únicamente para uso interno. No deben utilizarse en macros Basic.


¡Necesitamos su ayuda!