Рубрики
Без рубрики

Создание или удаление текстового поля в Word на Java

В этой статье показано, как вставлять или удалять текстовые поля в документе Word на Java. Помеченный java, word, текстовое поле.

В Word текстовое поле представляет собой подвижный контейнер с регулируемым размером для текста или графики. Мы можем добавлять текст, картинки, таблицы и другие объекты в текстовое поле. Текстовое поле является хорошим инструментом набора текста и может привлечь внимание читателей к содержимому текстового поля. В этой статье я покажу вам, как создать и удалить текстовое поле в документе Word с помощью FreeSpire. Документ для Java.

Добавить Spire.Doc.jar как зависимость

Способ 1: Скачать Бесплатный Шпиль. Документ для Java пакета, распакуйте его, и вы получите Spire.Doc.jar файл из папки “библиотека”. Импортируйте файл jar в свой проект в качестве зависимости.

Способ 2. Если вы создаете проект Maven, вы можете легко добавить зависимость jar, добавив следующие конфигурации в pom.xml .


        
            com.e-iceblue
            e-iceblue
            http://repo.e-iceblue.com/nexus/content/groups/public/
        


    
         e-iceblue 
        spire.doc.free
        2.7.3
    

Пример 1. Создайте текстовое поле

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 
        tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Page);
        tb.getFormat().setHorizontalPosition(50f);
        tb.getFormat().setVerticalOrigin(VerticalOrigin.Page);
        tb.getFormat().setVerticalPosition(20f);

        //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\\Poppies.jpg");
        picture.setHeight(125f);
        picture.setWidth(180f);
        para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        para.getFormat().setAfterSpacing(5f);

        //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");
        textRange.getCharacterFormat().setFontSize(12f);



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

Пример 2. Удалить текстовое поле

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 the document
        doc.saveToFile("RemoveTextbox.docx", FileFormat.Docx);
    }
}

Оригинал: “https://dev.to/eiceblue/create-or-remove-textbox-in-word-in-java-2a57”