Contenu
Index 🔎︎

# SFDocuments.Document service

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:

- Opening, closing and saving documents

- Accessing standard or custom properties of documents

The properties, methods or arguments marked with (*) are NOT applicable to Base documents.

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.

## Service invocation

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

##### En 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")

Directly if the document is already open.

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

From a macro triggered by a document event.

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

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()

##### En 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)
            # (...)

The use of the prefix "SFDocuments." while calling the service is optional.

## Properties

Name | Readonly | Type | Description
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 | Gives access to the Description property of the document (also known as "Comments")
DocumentProperties (*) | Yes | Dictionary service | Returns a ScriptForge.Dictionary object containing all the entries. Document statistics are included. Note that they are specific to the type of document. As an example, a Calc document includes a "CellCount" entry. Other documents do not.
DocumentType | Yes | String | String value with the document type ("Base", "Calc", "Writer", etc)
IsBase IsCalc IsDraw IsImpress IsMath IsWriter | Yes | Boolean | Exactly one of these properties is True for a given document.
Keywords (*) | No | String | Gives access to the Keywords property of the document. Represented as a comma-separated list of keywords
Readonly (*) | Yes | Boolean | True if the document is actually in read-only mode
Subject (*) | No | String | Gives access to the Subject property of the document.
Title (*) | No | String | Gives access to the Title property of the document.
XComponent | Yes | UNO Object | The UNO object com.sun.star.lang.XComponent or com.sun.star.comp.dba.ODatabaseDocument representing the document

### Exemple :

##### En 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()

##### En 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()

List of Methods in the Document Service
Activate CloseDocument ExportAsPDF | PrintOut RunCommand Save | SaveAs SaveCopyAs SetPrinter

## 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.

This method is useful when one needs to give focus for a document that is minimized or hidden.

### Syntaxe :

svc.Activate(): bool

### Exemple :

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

##### En Basic :

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

##### En Python

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

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.

### Syntaxe :

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

### Paramètres :

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.

### Exemple :

##### En Basic :

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

##### En Python

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

## ExportAsPDF

Exports the document directly as a PDF file to the specified location. Returns True if the PDF file was successfully created.

The export options can be set either manually using the File - Export As - Export as PDF dialog or by calling the methods GetPDFExportOptions and SetPDFExportOptions from the Session service.

### Syntaxe :

svc.ExportAsPDF(filename: str, overwrite: bool = False, opt pages: str, opt password: str, opt watermark: str): bool

### Paramètres :

filename: The full path and file name of the PDF to be created. It must follow the SF_FileSystem.FileNaming notation.

overwrite: Specifies if the destination file can be overwritten (Default = False). An error will occur if overwrite is set to False and the destination file already exists.

pages: String specifying which pages will be exported. This argument uses the same notation as in the dialog File - Export As - Export as PDF.

password: Specifies a password to open the PDF file.

watermark: Text to be used as watermark in the PDF file, which will be drawn in every page of the resulting PDF.

### Exemple :

##### En Basic :

The following example exports the current document as a PDF file, defines a password and overwrites the destination file if it already exists.

        oDoc.ExportAsPDF("C:\User\Documents\myFile.pdf", Password := "1234", Overwrite := True)

The code snippet below gets the current PDF export options and uses them to create the PDF file.

        Dim exportSettings as Object, oSession as Object
        oSession = CreateScriptService("Session")
        exportSettings = oSession.GetPDFExportOptions()
        ' Sets to True the option to export comments as PDF notes
        exportSettings.ReplaceItem("ExportNotes", True)
        oSession.SetPDFExportOptions(exportSettings)
        oDoc.ExportAsPDF("C:\User\Documents\myFile.pdf")

##### En Python

        doc.ExportAsPDF(r"C:\User\Documents\myFile.pdf", password = "1234", overwrite = True)

        session = CreateScriptService("Session")
        exportSettings = oSession.GetPDFExportOptions()
        exportSettings.ReplaceItem("ExportNotes", True)
        session.SetPDFExportOptions(exportSettings)
        doc.ExportAsPDF(r"C:\User\Documents\myFile.pdf")

## PrintOut

This method sends the contents of the document to the default printer or to the printer defined by the SetPrinter method.

Returns True if the document was successfully printed.

### Syntaxe :

svc.PrintOut(pages: str = "", copies: num = 1): bool

### Paramètres :

pages: The pages to print as a string, like in the user interface. Example: "1-4;10;15-18". Default is all pages.

copies: The number of copies. Default is 1.

### Exemple :

##### En Basic :

        If oDoc.PrintOut("1-4;10;15-18", Copies := 2) Then
            ' ...
        End If

##### En Python

        if doc.PrintOut(copies=3, pages='45-88'):
            # ...

## 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.

### Syntaxe :

svc.RunCommand(command: str)

### Paramètres :

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.

### Exemple :

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.

##### En Basic :

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

##### En 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.

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.

The document itself does not need to be active to run this method.

### Syntaxe :

svc.Save(): bool

### Exemple :

##### En Basic :

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

##### En 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.

The document itself does not need to be active to run this method.

### Syntaxe :

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

### Paramètres :

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.

### Exemple :

##### En Basic :

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

##### En Python

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

## SaveCopyAs

Stores a copy of or export the document to the given file location. The actual location is unchanged.

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.

The document itself does not need to be active to run this method.

### Syntaxe :

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

### Paramètres :

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.

### Exemple :

##### En Basic :

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

##### En Python

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

## SetPrinter

Defines the printer options for the document.

Returns True when successful.

### Syntaxe :

svc.SetPrinter(opt printer: str, opt orientation: str, paperformat: str): bool

### Paramètres :

printer: The name of the printer queue where to print to. When absent, the default printer is set.

orientation: Either PORTRAIT or LANDSCAPE. When absent, left unchanged with respect to the printer settings.

paperformat: Specifies the paper format as a string value that can be either A3, A4, A5, LETTER, LEGAL or TABLOID. Left unchanged when absent.

### Exemple :

##### En Basic :

        oDoc.SetPrinter(Orientation := "PORTRAIT")

##### En Python

        doc.SetPrinter(paperformat='TABLOID')

Toutes les routines ou identifiants de base ScriptForge qui sont préfixés par un caractère de soulignement "_" sont réservés à un usage interne. Ils ne sont pas destinés à être utilisés dans des macros de base ou des scripts Python.

Rubriques connexes

ScriptForge.UI service

ScriptForge.Dictionary service