This article demonstrates how to insert or remove a textbox in a Word document using Spire.Doc for Java.
Insert a text box
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) { //load a Word document Document doc = new Document(); doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //append a textbox to paragraph TextBox tb = doc.getSections().get(0).addParagraph().appendTextBox(100f, 350f); //set the text wrapping style tb.getFormat().setTextWrappingStyle(TextWrappingStyle.Square); //set the position of textbox tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Right_Margin_Area); tb.getFormat().setHorizontalPosition(-100f); tb.getFormat().setVerticalOrigin(VerticalOrigin.Page); tb.getFormat().setVerticalPosition(100f); //set the border style of textbox tb.getFormat().setLineStyle(TextBoxLineStyle.Thin_Thick); 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\\logo-2.png"); picture.setHeight(90f); picture.setWidth(80f); para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); para.getFormat().setAfterSpacing(15f); //insert text to textbox as the second paragraph para = tb.getBody().addParagraph(); TextRange textRange = para.appendText("E-iceblue Co. Ltd., a vendor of .NET, Java and WPF " +"development components, is dedicated to render developers tremendous potential " +"to deal with their files in .NET, Java and WPF applications."); textRange.getCharacterFormat().setFontName("Cambria"); textRange.getCharacterFormat().setFontSize(12f); para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); //save to file doc.saveToFile("InsertTextbox.docx", FileFormat.Docx_2013); } }
Remove a text box
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(); doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\textbox.docx"); //remove textbox by index doc.getTextBoxes().removeAt(0); //remove all //doc.getTextBoxes().clear(); //save to file doc.saveToFile("RemoveTextbox.docx", FileFormat.Docx); } }