Tenesta SFDocuments.Document

Biblioteket SFDocuments gjev metodar og eigenskapar for Ă„ letta handsaming og manipulering av LibreOffice-dokument.

Metodar som kan brukast pÄ alle typar av dokument (tekstdokument, rekneark, presentasjonar og sÄ vidare) vert leverte av tenesta SFDocuments.Document. Nokre eksempel er:

warning

Dei eigenskapane, metodane eller argumenta som er merkte med (*) kan IKKJE brukast pÄ database-dokument.


Metodar og eigenskapar som er spesifikke for LibreOffice-komponentar vert lagra i Ätskilde tenester, som for eksempel SFDocuments.SF_Calc og SFDocuments.SF_Base.

SjÞlv om Basic-sprÄket ikkje tilbyr nedarving mellom objektklassar, kan objektklassane sjÄast pÄ som underklasser av tenesta SFDocuments.Document. Slike underklassar kan kalla opp dei eigenskapane og metodane som er omtalte nedanfor.

Oppkall av tenester

Before using the Document service the ScriptForge library needs to be loaded or imported:

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


Nedanfor finn du tre ulike mÄtar Ä kalla opp tenesta Document.

I Basic

Med metoden getDocument frÄ tenesta ScriptForge.UI:


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

Du kan ogsÄ bruka metodane CreateDocument og OpenDocument frÄ tenesta UI.


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

Direkte viss dokumentet alt er opna.


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

FrÄ ein makro utlÞyst av ei dokument-hending.


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

Tenesta Document er i nĂŠr slekt med tenestene UI og FileSystem.


Bortsett frÄ nÄr dokumentet vart lukka av eit program med CloseDocument-metoden (det er dÄ overflÞdig),vert det tilrÄdd Ä frigjera ressursar etter bruk:


    Set oDoc = oDoc.Dispose()
  
I 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

Bruk av prefikset «SFDocuments.» ved oppkall av tenesta er frivillig.


Eigenskapar

Namn

Skriveverna

Type

Beskriving

CustomProperties (*)

Nei

Dictionary service

Returnerer ein objektfÞrekomst frÄ ScriptForge.Dictionary. Etter ei oppdatering kan den igjen sendast til den gjeldande eigenskapen som oppdaterer dokumentet.
Individuelle element i ordboka kan vera anten strenge, tal, (Basic-)dato eller com.sun.star.util.Duration-element.

Description (*)

Nei

String

Gjev tilgang til dokumenteigenskapen Description (ogsÄ kjend som «Nerknadar»)

DocumentProperties (*)

Ja

Dictionary service

Returnerer eit ScriptForge.Dictionary-objekt som inneheld alle oppfĂžringane. Dokumentstatistikk er inkludert. Legg merke til at dei er spesifikke for dokumenttypen. For eksempel inneheld eit Calc-dokument ei CellCount-oppfĂžring. Andre dokument gjer det ikkje.

DocumentType

Ja

String

Strengverdi med dokumenttypen («Base», «Calc», «Writer» og sÄ vidare)

IsBase
IsCalc
IsDraw
IsImpress
IsMath
IsWriter

Ja

Boolean

NÞyaktig éin av desse eigenskapane er Sann for eit gjeve dokument.

Keywords (*)

Nei

String

Gjev tilgang til nĂžkkelordeigenskapen for dokumentet. Representert som ei kommadelt liste over nĂžkkelord

Readonly (*)

Ja

Boolean

True viss dokumentet faktisk er i skriveverna tilstand

Subject (*)

Nei

String

Gjev tilgang til emne-eigenskapen for dokumentet.

Title (*)

Nei

String

Gjev tilgang til tittel-eigenskapen for dokumentet.

XComponent

Ja

UNO-objekt

UNO-objektet com.sun.star.lang.XComponent eller com.sun.star.comp.dba.ODatabaseDocument, som representerer dokumentet


Eksempel:

I Basic

Eksempelet nedanfor skriv ut alle eigenskapane brukte i dokument. Merk at objektet oDoc, som vert returnert av metoden UI.OpenDocument, er eit SFDocuments.Document-objekt.


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

For fÄ tilgang til dokumenteigenskapar i eit Python-skript som brukaren treng for Ä fÄ direkte tilgang til dei ved hjelp av namna, som vist nedanfor:


    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 over metodar i tenesta document

Activate
CloseDocument
CreateMenu
ExportAsPDF

PrintOut
RemoveMenu
RunCommand
Save

SaveAs
SaveCopyAs
SetPrinter


Activate

Returnerer Sann viss dokumentet kunne aktiverast. Elles er det inga endring i det faktiske brukargrensesnittet. Det svarar til metoden Activate i tenesta UI.

Denne metoden er nyttig nÄr ein mÄ fokusera pÄ eit dokument som er minimert eller gÞymd.

Syntaks:

svc.Activate(): bool

Eksempel:

Eksempelet nedanfor finn at fila «Mi_Fil.ods» alt er opna, men ikkje aktiv.

I Basic

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

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

Hugs at du kan kalla opp tenesta Document ved Ä overfÞra anten «Document» eller «SFDocuments.Document» til tenesta CreateScriptService


CloseDocument

Lukker dokumentet. Viss dokumentet alt er lukka, same korleis, har denne metode ingen verknad og returnerer Usann.

Metoden returnerer ogsÄ Usann viss brukaren avviser Ä lukka han.

Returnerer Sann viss det lukkast Ă„ lukka dokumentet.

Syntaks:

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

Parametrar:

saveask: Viss Sann (standard) vert brukaren beden om Ă„ stadfesta om endringane skal skrivast til lagringsmediumet. Argumentet vert ignorert om det ikkje er gjort endringar i dokumentet.

Eksempel:

I Basic

    If oDoc.CloseDocument(True) Then
        ' ...
    End If
  
I 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 LibreOfficeDev 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.


Syntaks:

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

Parametrar:

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

Eksempel:

I 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
  
I 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 LibreOfficeDev document windows.


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.

Syntaks:

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

Parametrar:

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.

Eksempel:

I 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")
  
I 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.

Syntaks:

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

Parametrar:

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.

Eksempel:

I Basic

    If oDoc.PrintOut("1-4;10;15-18", Copies := 2) Then
        ' ...
    End If
  
I 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.


Syntaks:

svc.RemoveMenu(menuheader: str): bool

Parametrar:

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

Eksempel:

I Basic

    Dim oDoc as Object
    Set oDoc = CreateScriptService("Document")
    oDoc.RemoveMenu("My Menu")
  
I 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 LibreOfficeDev 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.

Dokumentet treng ikkje vera aktivt for Ă„ kunna kĂžyra kommandoar.

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 LibreOfficeDev, refer to the Wiki page Development/DispatchCommands.


Syntaks:

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

Parametrar:

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.

Eksempel:

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


    ' Arguments passed to the command:
    ' 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.

I 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

Each LibreOfficeDev 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

Lagrar dokumentet der det vart henta frÄ. Metoden vert ignorert viss dokumentet ikkje er endra.

Returnerer Usann viss dokumentet ikkje kan lagrast. Det vert sett opp ein feil viss fila er opna som skriveverna eller viss det er ei ny fil utan namn.

Dokumentet treng ikkje vera aktivt for Ă„ bruk denne metoden.

Syntaks:

svc.Save(): bool

Eksempel:

I Basic

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

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

SaveAs

Lagrar dokumentet i den gjevne filplasseringa. Den nye plasseringa vert det nye filnamnet som vert brukt av det enkle metodekallet «Lagra».

Returnerer Usann viss dokumentet ikkje kan lagrast. Der vert sett opp ein feil viss mÄlet ikkje kan overskrivast eller nÄr mÄlet er skriveverna.

Dokumentet treng ikkje vera aktivt for Ă„ bruk denne metoden.

Syntaks:

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

Parametrar:

filnamn: Ein streng som inneheld det filnamnet som skal brukast. Namnet mÄ fÞlgja notasjonen SF_FileSystem.FileNaming.

overskriv: Viss Sann kan mÄlfila overskrivast (standard = Usann.

passord (*): Ein streng utan mellomrom som skal brukast for Ă„ verna dokumentet.

filternamn (*): Namnet pÄ eit filter som skal brukast for Ä lagra dokumentet. Viss argumentet vert sendt vidare, mÄ filteret finnast.

filterinnstillingar (*): Ein valfri streng med innstillingar for dette filteret.

Eksempel:

I Basic

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

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

SaveCopyAs

Lagrar ein kopi eller eksporterer dokumentet til den gjevne filplasseringa. Den aktuelle plasseringa vert ikkje endra.

Returnerer Usann viss dokumentet ikkje kan lagrast. Der vert sett opp ein feil viss mÄlet ikkje kan overskrivast eller nÄr mÄlet er skriveverna.

Dokumentet treng ikkje vera aktivt for Ă„ bruk denne metoden.

Syntaks:

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

Parametrar:

filnamn: Ein streng som inneheld det filnamnet som skal brukast. Namnet mÄ fÞlgja notasjonen SF_FileSystem.FileNaming.

overskriv: Viss Sann kan mÄlfila overskrivast (standard = Usann.

passord (*): Ein streng utan mellomrom som skal brukast for Ă„ verna dokumentet.

filternamn (*): Namnet pÄ eit filter som skal brukast for Ä lagra dokumentet. Viss argumentet vert sendt vidare, mÄ filteret finnast.

filterinnstillingar (*): Ein valfri streng med innstillingar for dette filteret.

Eksempel:

I Basic

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

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

SetPrinter

Defines the printer options for the document.

Returns True when successful.

Syntaks:

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

Parametrar:

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.

Eksempel:

I Basic

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

    doc.SetPrinter(paperformat='TABLOID')
  
warning

Alle ScriptForge Basic-rutinane og -identifikatorane som vert innleidde med understrek «_» er reserverte for internt bruk. Dei er ikkje meint brukte i Basic-makroar.