Servizio SFDocuments.Document

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

I metodi applicabili a tutti i tipi di documento (documenti di testo, fogli elettronici, presentazioni, ecc.) sono forniti dal servizio SFDocuments.Document. Alcuni esempi sono:

warning

Le proprietà, i metodi e gli argomenti contrassegnati con (*) NON sono applicabili ai documenti di 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.

Anche se il linguaggio Basic non offre l'ereditarietà tra le classi di oggetti, gli ultimi servizi possono essere considerati come sottoclassi del servizio SFDocuments.Document. Queste sottoclassi possono invocare le proprietà e i metodi descritti di seguito.

Invocare il servizio

Prima di usare il servizio Document è necessario caricare o importare le librerie ScriptForge:

note

• Basic macros require to load ScriptForge library using the following statement:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Python scripts require an import from scriptforge module:
from scriptforge import CreateScriptService


Di seguito sono riportate tre varianti del modo in cui è possibile invocare il servizio Document.

In Basic

Usando il metodo getDocument dal servizio ScriptForge.UI:


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

In alternativa potete usare i metodi CreateDocument e OpenDocument dal servizio UI.


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

Direttamente se il documento è già aperto.


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

Da una macro attivata da un evento del documento.


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

Il servizio Document è strettamente collegato ai servizi UI e FileSystem.


Eccetto quando il documento è stato chiuso da un programma usando il metodo CloseDocument (che lo rende superfluo), si consiglia di liberare le risorse dopo l'uso:


    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

L'uso del prefisso "SFDocuments." nella chiamata al servizio è opzionale.


Proprietà

Nome

Sola lettura

Tipo

Descrizione

CustomProperties (*)

No

Dictionary service

Restituisce un'istanza dell'oggetto ScriptForge.Dictionary. Dopo il suo aggiornamento, può essere passata nuovamente alla proprietà affinché aggiorni in documento.
I singoli elementi del dizionario possono essere stringhe, numeri, date (di Basic) o elementi com.sun.star.util.Duration.

Description (*)

No

String

Fornisce accesso alla proprietà "Description" del documento (chiamata anche "Comments")

DocumentProperties (*)

Dictionary service

Restituisce un oggetto ScriptForge.Dictionary contenente tutte le voci. Sono comprese le statistiche del documento. Si noti che queste sono specifiche del tipo di documento. Per esempio, un documento di Calc comprende una voce "CellCount". Altri documenti no.

DocumentType

String

Un valore in formato stringa con il tipo di documento ("Base", "Calc", "Writer", ecc.)

ExportFilters

Yes

String array

Returns a list with the export filter names applicable to the current document as a zero-based array of strings. Filters used for both import/export are also returned.

ImportFilters

Yes

String array

Returns a list with the import filter names applicable to the current document as a zero-based array of strings. Filters used for both import/export are also returned.

IsBase
IsCalc
IsDraw
IsImpress
IsMath
IsWriter

Boolean

Solamente una di queste proprietà è True per un determinato documento.

Keywords (*)

No

String

Fornisce l'accesso alla proprietà Keywords del documento. Rappresentata come un elenco di parole chiave separate da virgola

Readonly (*)

Boolean

True se il documento è effettivamente in modalità sola lettura

Subject (*)

No

String

Fornisce accesso alla proprietà Subject del documento.

Title (*)

No

String

Fornisce accesso alla proprietà Title del documento.

XComponent

Oggetto UNO

L'oggetto UNO com.sun.star.lang.XComponent o com.sun.star.comp.dba.ODatabaseDocument che rappresenta il documento


Esempio:

In Basic

L'esempio sottostante stampa tutte le proprietà di un documento. Si noti che l'oggetto oDoc restituito dal metodo UI.OpenDocument è un oggetto 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()
  
In Python

Per accedere alle proprietà del documento in uno script in Python l'utente deve accedervi direttamente usando i loro nomi, come mostrato di seguito:


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

Elenco dei metodi del servizio Document

Activate
CloseDocument
CreateMenu
ExportAsPDF

PrintOut
RemoveMenu
RunCommand
Save

SaveAs
SaveCopyAs
SetPrinter


Activate

Restituisce True se il documento può essere attivato. Altrimenti, non c'è alcuna modifica all'interfaccia utente. È equivalente al metodo Activate del servizio UI.

Questo metodo è utile quando si rende necessario portare in primo piano un documento ridotto a icona o nascosto.

Sintassi:

svc.Activate(): bool

Esempio:

L'esempio sottostante considera il file "My_File.ods" già aperto ma non attivo.

In Basic

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

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

Tenete presente che potete invocare il servizio Document passando a CreateScriptService sia "Document" sia "SFDocuments.Document"


CloseDocument

Chiude il documento. Se il documento è già chiuso, indipendentemente da come è stato chiuso, questo metodo non ha effetto e restituisce False.

Il metodo restituirà False anche se l'utente non accetta la sua chiusura.

Restituisce True se il documento è stato chiuso correttamente.

Sintassi:

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

Parametri:

saveask: se è True (predefinito), l'utente viene invitato a confermare se le modifiche devono essere salvate su disco. Questo argomento viene ignorato se il documento non è stato modificato.

Esempio:

In Basic

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

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

CreateMenu

Creates a new menu entry in the menubar of a given document window.

This method returns an instance of the SFWidgets.Menu service.

note

The menu created is only available during the current LibreOffice session and is not saved neither in the document nor in the global application settings. Hence closing the document window will make the menu disappear. It will only reappear when the macro that creates the menu is executed again.


Sintassi:

svc.CreateMenu(menuheader: str, [before: any], submenuchar: str = ">"): svc

Parametri:

menuheader: The toplevel name of the new menu.

before: The name (as a string) or position (as an integer starting at 1) of an existing menu before which the new menu will be placed. If no value is defined for this argument, the menu will be created at the last position in the menubar.

submenuchar: The delimiter used to create menu trees when calling methods as AddItem from the Menu service. The default value is ">".

Esempio:

In Basic

    Dim oDoc as Object, oMenu as Object
    Set oDoc = CreateScriptService("Document")
    Set oMenu = oDoc.CreateMenu("My Menu")
    With oMenu
        ' Add items to the menu
        .AddItem("Item A")
        .AddItem("Item B")
        ' ...
        ' After creating the menu, the service instance can be disposed of
        .Dispose()
    End With
  
In Python

    doc = CreateScriptService("Document")
    menu = doc.CreateMenu("My Menu")
    menu.AddItem("Item A")
    menu.AddItem("Item B")
    # ...
    menu.Dispose()
  
tip

Refer to the SFWidgets.Menu help page to learn more about how to create/remove menus in LibreOffice document windows.


ExportAsPDF

Esporta direttamente il documento in un file PDF, nel percorso specificato. Se il file è creato correttamente restituisce True.

Le opzioni di esportazione possono essere impostate sia manualmente, usando la finestra di dialogo File - Esporta come - Esporta nel formato PDF, sia chiamando i metodi GetPDFExportOptions e SetPDFExportOptions del servizio Session.

Sintassi:

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

Parametri:

filename: il nome completo del percorso e del file PDF da creare. Deve conformarsi alla notazione SF_FileSystem.FileNaming.

overwrite: specifica se il file di destinazione può essere sovrascritto (predefinito = False). Se overwrite è impostato su False e il file di destinazione esiste già, si verificherà un errore.

pages: stringa che specifica le pagine da esportare. Questo argomento usa la stessa notazione della finestra di dialogo File - Esporta come - Esporta nel formato PDF.

password: specifica una password per aprire il file PDF.

watermark: testo da usare come filigrana nel file PDF che sarà visualizzato su ogni pagina del PDF risultante.

Esempio:

In Basic

L'esempio seguente esporta il documento corrente come file PDF, definisce una password e sovrascrive il file di destinazione, se questo esiste già.


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

Il frammento di codice sottostante recupera le opzioni di esportazione in PDF correnti e le usa per creare il file PDF.


    Dim exportSettings as Object, oSession as Object
    oSession = CreateScriptService("Session")
    exportSettings = oSession.GetPDFExportOptions()
    ' Imposta a True l'opzione per esportare i commenti come note del PDF
    exportSettings.ReplaceItem("ExportNotes", True)
    oSession.SetPDFExportOptions(exportSettings)
    oDoc.ExportAsPDF("C:\User\Documents\myFile.pdf")
  
In 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

Questo metodo invia i contenuti del documento alla stampante predefinita o a quella impostata dal metodo SetPrinter.

Restituisce True se il documento è stato stampato correttamente.

Sintassi:

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

Parametri:

pages: le pagine da stampare in formato stringa, come nell'interfaccia utente. Esempio "1-4;10;15-18". L'impostazione predefinita è tutte le pagine.

copies: il numero di copie. Il valore predefinito è 1.

Esempio:

In Basic

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

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

RemoveMenu

Removes a toplevel menu from the menubar of a given document window.

Returns True if the specified menu could be removed. If the specified menu does not exist, the method returns False.

note

This method can be used to remove any menu entry from the document window, including default menus. However, none of these changes in the menubar are saved to the document or to the application settings. To restore the menubar to the default settings, simply close and reopen the document window.


Sintassi:

svc.RemoveMenu(menuheader: str): bool

Parametri:

menuheader: The toplevel name of the menu to be removed.

Esempio:

In Basic

    Dim oDoc as Object
    Set oDoc = CreateScriptService("Document")
    oDoc.RemoveMenu("My Menu")
  
In Python

    doc = CreateScriptService("Document")
    doc.RemoveMenu("My Menu")
  
tip

Refer to the SFWidgets.Menu help page to learn more about how to create/remove menus in LibreOffice document windows.


RunCommand

Runs a UNO command on the document window associated with the service instance. A few typical commands are: Save, SaveAs, ExportToPDF, Undo, Copy, Paste, etc.

Per eseguire comandi, il documento non deve necessariamente essere attivo.

Commands can be run with or without arguments. Arguments are not validated before running the command. If the command or its arguments are invalid, then nothing will happen.

tip

For a complete list of UNO commands that can be run in LibreOffice, refer to the Wiki page Development/DispatchCommands.


Sintassi:

svc.RunCommand(command: str, [args: any])

Parametri:

command: Case-sensitive string containing the UNO command name. The inclusion of the prefix ".uno:" in the command is optional. The command itself is not checked for correctness. If nothing happens after the command call, then the command is probably wrong.

args: For each argument to be passed to the command, specify a pair containing the argument name and value.

Esempio:

In Basic

The following example runs the SelectData command in a Calc file named "MyFile.ods", which will result in the selection of the data area based on the currently selected cell. Note that this command does not require any arguments.


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

Below is an example that runs the UNO command ReplaceAll and passes values for its arguments SearchString and ReplaceString. Running this command will replace all occurrence of the string "abc" by "ABC" in the current sheet.


    ' Argomenti passati al comando:
    ' SearchString  = "abc"
    ' ReplaceString = "ABC"
    oDoc.RunCommand(".uno:ReplaceAll", "SearchString", "abc", "ReplaceString", "ABC")
  

Note that calling the command ReplaceAll without arguments will open the Find and Replace dialog.

In Python

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

    doc.RunCommand(".uno:ReplaceAll", "SearchString", "abc", "ReplaceString", "ABC")
  

In Python it is also possible to call RunCommand using keyword arguments:


    doc.RunCommand(".uno:ReplaceAll", SearchString = "abc", ReplaceString = "ABC")
  
tip

Ogni componente di LibreOffice dispone di un proprio insieme di comandi. Un modo semplice per imparare i comandi è quello di accedere a Strumenti - Personalizza - Tastiera. Quando posizionate il cursore del mouse sopra una funzione nell'elenco Funzione comparirà un suggerimento con il comando UNO corrispondente.


Save

Memorizza il documento nella posizione del file da cui è stato caricato. Il metodo viene ignorato se il documento non è stato modificato.

Restituisce False se il documento non può essere salvato. Viene generato un errore se il file è aperto in sola lettura o se il nuovo file non è stato ancora salvato.

Per eseguire questo metodo non è necessario che il documento in questione sia attivo.

Sintassi:

svc.Save(): bool

Esempio:

In Basic

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

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

SaveAs

Memorizza il documento in un file nella posizione specificata. La nuova posizione diventa il nuovo nome di file sul quale verranno applicate le chiamate al metodo "Save" semplice.

Restituisce False se il documento non può essere salvato. Viene sollevato un errore se la sovrascrittura della destinazione viene rifiutata o quando per la destinazione è impostato l'attributo di sola lettura.

Il documento in questione non deve essere attivo per poter eseguire questo metodo.

Sintassi:

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

Parametri:

filename: una stringa contenente il nome del file da usare. Deve rispettare la notazione SF_FileSystem.FileNaming.

overwrite: se è True, il file di destinazione può essere sovrascritto (predefinito = False).

password (*): una stringa priva di spazi con la quale proteggere il documento.

filtername (*): il nome di un filtro da usare per salvare il documento. Se questo argomento viene passato, allora il filtro deve esistere.

filteroptions (*): una stringa facoltativa delle opzioni associate al filtro.

Esempio:

In Basic

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

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

SaveCopyAs

Memorizza una copia o esporta il documento nel percorso specificato del file. Il file nella posizione corrente rimane immutato.

Restituisce False se il documento non può essere salvato. Viene sollevato un errore se la sovrascrittura della destinazione viene rifiutata o quando per la destinazione è impostato l'attributo di sola lettura.

Non è necessario che il documento in questione sia attivo per eseguire questo metodo.

Sintassi:

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

Parametri:

filename: una stringa contenente il nome del file da usare. Deve rispettare la notazione SF_FileSystem.FileNaming.

overwrite: Se è True, il file di destinazione può essere sovrascritto (predefinito = False).

password (*): una stringa priva di spazi con la quale proteggere il documento.

filtername (*): Il nome di un filtro da usare per salvare il documento. Se questo argomento viene passato, allora il filtro deve esistere.

filteroptions (*): una stringa facoltativa delle opzioni associate al filtro.

Esempio:

In Basic

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

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

SetPrinter

Definisce le opzioni di stampa per il documento.

Il metodo restituisce True se eseguito correttamente.

Sintassi:

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

Parametri:

printer: il nome della coda della stampante su cui stampare. Se assente, viene impostata la stampante predefinita.

orientation: uno tra PORTRAIT (verticale) o LANDSCAPE (orizzontale). Se non è presente, le impostazioni della stampante restano immutate.

paperformat: specifica il formato della carta come stringa il cui valore può essere A3, A4, A5, LETTER, LEGAL o TABLOID. Se assente, non viene cambiato.

Esempio:

In Basic

    oDoc.SetPrinter(Orientation := "PORTRAIT")
  
In Python

    doc.SetPrinter(paperformat='TABLOID')
  
warning

Tutte le routine e gli identificatori Basic di ScriptForge che iniziano con un carattere di sottolineatura "_" sono riservati per uso interno. Non è previsto il loro utilizzo nelle macro in Basic o negli script in Python.