在Word文檔中,文本框是指一種可移動、可調大小的文字或圖形容器。使用文本框,可以使文檔在內容和形式上更爲飽滿。本文將經過使用Java編程來演示如何添加、刪除Word文檔中的文本框。html
使用工具:Free Spire.Doc for Java (免費版)java
Jar文件獲取及導入:編程
方法1:經過官網下載獲取Jar包。下載後,解壓文件,並將lib文件夾下的Spire.Doc.Jar文件導入Java程序。(以下圖)app
方法2:經過maven倉庫安裝導入。maven
添加文本框工具
Java代碼示例:spa
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) { //加載Word文檔 Document doc = new Document(); doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx"); //添加文本框 TextBox tb = doc.getSections().get(0).getParagraphs().get(0).appendTextBox(100f, 350f); //設置文字環繞方式 tb.getFormat().setTextWrappingStyle(TextWrappingStyle.Square); //設置文本框的相對位置 tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Right_Margin_Area); tb.getFormat().setHorizontalPosition(-100f); tb.getFormat().setVerticalOrigin(VerticalOrigin.Page); tb.getFormat().setVerticalPosition(100f); //設置文本框邊框樣式 tb.getFormat().setLineStyle(TextBoxLineStyle.Thin_Thick); tb.getFormat().setLineColor(new Color(240,135,152)); //插入圖片到文本框 Paragraph para = tb.getBody().addParagraph(); DocPicture picture = para.appendPicture("C:\\Users\\Test1\\Desktop\\Image.jpg"); picture.setHeight(90f); picture.setWidth(80f); para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); para.getFormat().setAfterSpacing(15f); //插入文字到文本框 para = tb.getBody().addParagraph(); TextRange textRange = para.appendText("聖誕老人,是一位身穿紅袍、頭戴紅帽的白鬍子老頭。" + "每一年聖誕節他駕着鹿拉的雪橇從北方而來,由煙囪進入各家,把聖誕禮物裝在襪子裏掛在孩子們的牀頭上或火爐前。 "); textRange.getCharacterFormat().setFontName("宋體"); textRange.getCharacterFormat().setFontSize(12f); para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); //保存文檔 doc.saveToFile("output/InsertTextbox.docx", FileFormat.Docx_2013); } }
文本框添加效果:code
刪除文本框orm
Java代碼示例:htm
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemoveTextBox { public static void main(String[] args) { //加載含有文本框的Word文檔 Document doc = new Document(); doc.loadFromFile("C:\\Users\\Test1\\Desktop\\RemoveTextbox.docx"); //經過索引移除文本框 doc.getTextBoxes().removeAt(0); //移除全部文本框 doc.getTextBoxes().clear(); //保存文檔 doc.saveToFile("output/RemoveTextbox.docx", FileFormat.Docx); } }
文本框刪除效果:
(本文完)