DEV Community


Create or Remove Textbox in Word in Java

eiceblue profile image E-iceblue Product Family ・2 min read

In Word, a textbox is a movable, size adjustable container for text or graphics. We can add text, pictures, tables and other objects to the text box. Textbox is a good typesetting tool, and can attract readers to pay attention to the content of textbox. In this article, I’m going to show you how to create and remove a textbox in a Word document using Free Spire.Doc for Java.

Add Spire.Doc.jar as dependency

Method 1: Download Free Spire.Doc for Java pack, unzip it and you’ll get Spire.Doc.jar file from the “lib” folder. Import the jar file in your project as a dependency.

Method 2: If you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.

        <groupId> e-iceblue </groupId>

Example 1. Create a textbox

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class InsertTextbox {

    public static void main(String[] args) {

        //Create a Document object 
        Document doc = new Document();

        //Add a section
        Section section = doc.addSection();

        //Append a textbox 
        TextBox tb = section.addParagraph().appendTextBox(200f, 220f);

        //Set the relative position of textbox 

        //Set the border style of textbox 
        tb.getFormat().setLineColor(new Color(240,135,152));

        //Insert an image to textbox as a paragraph 
        Paragraph para = tb.getBody().addParagraph();
        DocPicture picture = para.appendPicture("C:\\Users\\Administrator\\Desktop\\Poppies.jpg");

        //Insert text to textbox as the second paragraph
        para = tb.getBody().addParagraph();
        TextRange textRange = para.appendText("A poppy is a flowering plant in the subfamily Papaveroideae of the family Papaveraceae."
                +" Poppies are herbaceous plants, often grown for their colourful flowers.");
        textRange.getCharacterFormat().setFontName("Times New Roman");

        //Save to file 
        doc.saveToFile("CreateTextbox.docx", FileFormat.Docx_2013);

Alt Text

Example 2. Remove a textbox

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class DeleteTextbox {

    public static void main(String[] args) {

        //Load the Word document containing textbox
        Document doc = new Document();

        //Remove textbox by index

        //Remove all

        //Save the document
        doc.saveToFile("RemoveTextbox.docx", FileFormat.Docx);

Discussion (0)

Editor guide