SFDocuments.Document service

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

Les méthodes applicables à tous les types de documents (Documents Textes, Classeurs, Présentations, etc.) sont fournies par le service SFDocuments.Document. Certains exemples sont :

warning

Les propriétés, méthodes ou arguments marqués d'un (*) ne sont PAS applicables aux documents 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.

Bien que le langage Basic ne propose pas d'héritage entre classes d'objets, ces derniers services peuvent être considérés comme des sous-classes du service SFDocuments.Document. Ces sous-classes peuvent invoquer les propriétés et les méthodes décrites ci-dessous.

Invocation du service

Vous trouverez ci-dessous trois variantes de la façon dont le service Document peut être appelé.

En Basic :

Utilisation de la méthode getDocument du service ScriptForge.UI :


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

Vous pouvez également utiliser les méthodes CreateDocument et OpenDocument du service UI.


    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
  

À partir d'une macro déclenchée par un événement de document.


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

Le service Document est étroitement lié aux services UI et FileSystem.


Sauf lorsque le document a été fermé par programme avec la méthode CloseDocument (c'est alors superflu), il est recommandé de libérer des ressources après utilisation :


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

L'utilisation du préfixe "SFDocuments." lors de l'appel du service est facultative.


Propriétés

Nom

En lecture seule

Type

Description

CustomProperties (*)

Non

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

Non

String

Donne accès à la propriété Description du document (également appelée "Comments")

DocumentProperties (*)

Oui

Dictionary service

Renvoie un objet ScriptForge.Dictionary contenant toutes les entrées. Les statistiques du document sont incluses. Notez qu'elles sont spécifiques au type de document. Par exemple, un document Calc inclut une entrée "CellCount". D'autres documents ne les ont pas.

DocumentType

Oui

String

Valeur de chaîne avec le type de document ("Base", "Calc", "Writer", etc.)

IsBase
IsCalc
IsDraw
IsImpress
IsMath
IsWriter

Oui

Boolean

Exactement une de ces propriétés est True pour un document donné.

Keywords (*)

Non

String

Donne accès à la propriété Keywords du document. Représenté sous la forme d'une liste de mots-clés séparés par des virgules

Readonly (*)

Oui

Boolean

True si le document est réellement en mode lecture seule

Subject (*)

Non

String

Donne accès à la propriété Subject du document.

Title (*)

Non

String

Donne accès à la propriété Title du document.

XComponent

Oui

Objets UNO

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


Exemple :

En Basic :

L'exemple ci-dessous imprime toutes les propriétés d'un document. Notez que l'objet oDoc renvoyé par la méthode UI.OpenDocument est un objet SFDocuments.Document.


    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

Pour accéder aux propriétés du document dans un script Python, l'utilisateur doit y accéder directement en utilisant leurs noms, comme indiqué ci-dessous :


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

Liste des méthodes dans le service Document

Activate
CloseDocument
ExportAsPDF

PrintOut
RunCommand
Save

SaveAs
SaveCopyAs
SetPrinter


Activate

Renvoie True si le document peut être activé. Sinon, il n'y a aucun changement dans l'interface utilisateur active. Elle est équivalente à la méthode Activate du service UI.

Cette méthode est utile lorsque l'on doit donner le focus à un document réduit ou masqué.

Syntaxe :

svc.Activate(): bool

Exemple :

L'exemple ci-dessous considère que le fichier "My_File.ods" est déjà ouvert mais pas actif.

En Basic :

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

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

Gardez à l'esprit que vous pouvez invoquer le service Document en passant à CreateScriptService "Document" ou "SFDocuments.Document"


CloseDocument

Ferme le document. Si le document est déjà fermé, quelle que soit la façon dont le document a été fermé, cette méthode n'a aucun effet et renvoie False.

La méthode renverra également False si l'utilisateur refuse de le fermer.

Renvoie True si le document a été fermé avec succès.

Syntaxe :

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

Paramètres :

saveask : si True (par défaut), l'utilisateur est invité à confirmer si les modifications doivent être écrites sur le disque. Cet argument est ignoré si le document n'a pas été modifié.

Exemple :

En Basic :

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

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

ExportAsPDF

Exporte le document directement sous forme de fichier PDF à l'emplacement spécifié. Renvoie True si le fichier PDF a été créé avec succès.

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 : chemin d'accès complet et nom de fichier du PDF à créer. Il doit suivre la notation SF_FileSystem.FileNaming.

overwrite : spécifie si le fichier de destination peut être écrasé (par défaut = False). Une erreur se produira si overwrite est défini sur False et que le fichier de destination existe déjà.

pages : chaîne spécifiant quelles pages seront exportées. Cet argument utilise la même notation que dans la boîte de dialogue Fichier - Exporter sous - Exporter au format PDF.

password : spécifie un mot de passe pour ouvrir le fichier PDF.

watermark : texte à utiliser comme filigrane dans le fichier PDF, qui sera dessiné sur chaque page du PDF résultant.

Exemple :

En Basic :

L'exemple suivant exporte le document actuel sous forme de fichier PDF, définit un mot de passe et écrase le fichier de destination s'il existe déjà.


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

L'extrait de code ci-dessous récupère les options d'export PDF actuelles et les utilise pour créer le fichier PDF.


    Dim exportSettings as Object, oSession as Object
    oSession = CreateScriptService("Session")
    exportSettings = oSession.GetPDFExportOptions()
    ' Définit sur True l'option d'export des commentaires sous forme de notes PDF
    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

Cette méthode envoie le contenu du document à l'imprimante par défaut ou à l'imprimante définie par la méthode SetPrinter.

Renvoie True si le document a été imprimé avec succès.

Syntaxe :

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

Paramètres :

pages : les pages à imprimer sous forme de chaîne, comme dans l'interface utilisateur. Exemple : "1-4;10;15-18". La valeur par défaut est toutes les pages.

copies : le nombre de copies. La valeur par défaut est 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.

Le document lui-même n'a pas besoin d'être actif pour pouvoir exécuter des commandes.

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.

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.

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')
  
warning

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.


Aidez-nous !