This tutorial will show how to save a LibreOffice Calc sheet directly as a pdf file using basic macro. In many automation task this simple feature frequently required.
Writing the Macro
Lets call the function as “exportToPDF()” that we will hold the entire process.
First define two objects which would hold the Calc document and a dispatch to execute actions.
dim document as object
dim dispatcher as object
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
Now create an empty file using basic’s “Open” function. Note that the path is of the file system path. Thus we have prefixed the path with “file://”. Once the file is created, close the file.
path ="file:///home/arindam/sheet1.pdf"
Open path For Append As #1
Close #1
Now, create an array of size 1 to hold the property value for exporting as pdf. Then fill the property in the array of name “URL” with the path of the file we just created.
dim args1(0) as new com.sun.star.beans.PropertyValue
args1(0).Name = "URL"
args1(0).Value = "file:///home/arindam/sheet1.pdf"
Finally call the executeDispatch method to put the sheet1 content to the pdf and save.
dispatcher.executeDispatch(document, ".uno:ExportDirectToPDF", "", 0, args1())
This completes the code.
The complete function is present below.
Sub ExportToPDF()
dim document as object
dim dispatcher as object
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
' change the path below as per your needs
path ="file:///home/arindam/sheet1.pdf"
Open path For Append As #1
Close #1
dim args1(0) as new com.sun.star.beans.PropertyValue
args1(0).Name = "URL"
args1(0).Value = "file:///home/arindam/sheet1.pdf" ' change the path below as per your needs
dispatcher.executeDispatch(document, ".uno:ExportDirectToPDF", "", 0, args1())
End Sub
Running the save as pdf function
Open LibreOffice calc and Create a macro and put the above function. Write anything in the sheet1. For this example, I have written something like this –
Run the macro
You can see the entire sheet1 content is saved in the specified directory mentioned in above macro. Here is the content of the pdf that is created using this macro.
Drop a comment using below comment box, if you faced any problem using this.