Editing Text Box

This guide explains the process of obtaining, editing and creating text boxes in a Presentation files using UniOffice. It follows an example from the unioffice-examples and explains the code step by step.

Sample input

sample input

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniOffice SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unioffice-examples

To get the example navigate to the path presentation/textbox folder in the unioffice-examples directory.

cd unioffice-examples/presentation/textbox/

How it works

The code starts by defining the package and then importing the necessary libraries and packages in the import section. The init function in lines 13-20, sets the license key which is necessary to use the library.

The next part of the code is the main function which is defined in lines 22-56. In this function, the code in line opens the presentation file using presentation.Open("source.pptx"). Then line 28, obtains the first slide from the opened presentation. This is achieved by calling the Slides method of the presentation object and then specifying the slide index. In lines 31-39, the text boxes are obtained from slide and then the contents are printed by iterating through each text box. This is done using:

tbs := slide.GetTextBoxes() // getting all textboxes
for _, tb := range tbs {
  for _, p := range tb.X().TxBody.P {
    for _, tr := range p.EG_TextRun {

The code in lines 42-44, edits the text of an existing text-box. This is done in three steps. First in line 42, the target text box is obtained using tbs[0]. Next the dml.CT_RegularTextRun is obtained in line 43. Then the text field of the Run is set in line 44, using run.T = "Edited TextBox text".

The next section, i.e. lines 47-53 creates a new text-box using:

newTb := slide.AddTextBox()
newTb.SetOffsetX(measurement.Inch * 5)
newTb.SetOffsetY(measurement.Inch * 4)

newPara := newTb.AddParagraph()
newRun := newPara.AddRun()
newRun.SetText("New TextBox text")

In the above snippet, first a new text-box is added using AddTextBox method of the presentation.Slide object. Then X, Y offset of the presentation.TextBox are set using SetOffsetX and SetOffsetY methods. The rest of the snippet creates a new paragraph, then instantiates a new run and finally sets the text content of the new TextBox.

Finally, the modified presentation is written to file in line 55 using ppt.SaveToFile("mod.pptx").

Run the code

Run this command to generate the presentation file with a table.

go run main.go

Sample output

I am a TextBox 1
I am a TextBox 2
I am a TextBox 3

Modified presentation.

modified presentation

Got any Questions?

We're here to help you.