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

Создание полей формы в Word на Java

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

Вы можете создать шаблон документа Word с устаревшими полями формы, которые могут заполнять другие пользователи. В принципе, в Microsoft Word существует три типа устаревших типов полей форм:

  1. Поле Текстовой Формы
  2. Поле формы флажка
  3. Поле Раскрывающейся формы

В этой статье я расскажу, как создать текст, поля флажков и выпадающих форм в документе Word на Java с помощью Free Spire. Документ для Java библиотека.

Добавление зависимостей

Прежде всего, вам нужно добавить необходимые зависимости для включения Free Spire. Doc для Java в ваш Java-проект. Есть два способа сделать это. Если вы используете maven, вам необходимо добавить следующий код в свой проект pom.xml файл.

  
          
            com.e-iceblue  
            e-iceblue  
            http://repo.e-iceblue.com/nexus/content/groups/public/  
          
  
  
      
        e-iceblue  
        spire.doc.free  
        2.7.3  
      
  

Для проектов, не связанных с maven, скачайте бесплатный Spire. Документ для пакета Java с этого веб-сайта и добавьте Spire.Doc.jar в папке lib в вашем проекте в качестве зависимости.

Создание Полей Формы

Свободный дух. Doc для Java API предоставляет Paragraph.append Field метод для создания полей формы в Word. После добавления полей формы вы можете защитить документ с помощью метода Document.protect , чтобы пользователи могли заполнять только поля формы в документе. В следующем примере вы увидите, как добавить поля формы в документ Word и защитить документ с помощью этого API.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.CheckBoxFormField;
import com.spire.doc.fields.DropDownFormField;
import com.spire.doc.fields.TextFormField;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class CreateFormFields {
    public static void main(String[] args) throws Exception {
        //Create a Document instance
        Document doc = new Document();
        //Add a section
        Section section = doc.addSection();

        //Add a title paragraph
        Paragraph title = section.addParagraph();
        TextRange titleText = title.appendText("Employee Information");
        titleText.getCharacterFormat().setFontName("Calibri");
        titleText.getCharacterFormat().setFontSize(16f);
        title.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Create a table
        Table table = section.addTable(true);
        table.resetCells(5, 2);

        //Merge cells in the first row
        table.applyHorizontalMerge(0, 0, 1);

        //Set table header
        TableRow headerRow = table.getRows().get(0);
        headerRow.isHeader(true);
        headerRow.getRowFormat().setBackColor(new Color(0x00, 0x71, 0xb6));
        headerRow.getCells().get(0).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
        Paragraph headerParagraph = headerRow.getCells().get(0).addParagraph();
        TextRange headerText = headerParagraph.appendText("Personal Information");
        headerText.getCharacterFormat().setBold(true);

        //Add paragraph to table cell [1,0]
        Paragraph paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
        TextRange textRange = paragraph.appendText("Full name");

        //Add paragraph to table cell [1,1] and append a text form field to the paragraph
        paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
        TextFormField textForm = (TextFormField)paragraph.appendField("FullName", FieldType.Field_Form_Text_Input);
        //Add paragraph to table cell [2,0]
        paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
        textRange = paragraph.appendText("Age");
        //Add paragraph to table cell [2,1] and append a text form field
        paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
        textForm = (TextFormField)paragraph.appendField("Age", FieldType.Field_Form_Text_Input);

        //Add paragraph to table cell [3,0] 
        paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
        textRange = paragraph.appendText("Married");
        //Add paragraph to table cell [3,1] and append a check box  form field
        paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
        CheckBoxFormField checkboxForm = (CheckBoxFormField)paragraph.appendField("Married", FieldType.Field_Form_Check_Box);
        checkboxForm.setCheckBoxSize(8);

        //Add paragraph to table cell [4,0] 
        paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
        textRange = paragraph.appendText("Gender");
        //Add paragraph to table cell [4,1] and append a drop down  form field
        paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
        DropDownFormField dropdownField = (DropDownFormField)paragraph.appendField("DropDown",FieldType.Field_Form_Drop_Down);
        dropdownField.getDropDownItems().add("Male");
        dropdownField.getDropDownItems().add("Female");

        for (int i = 0; i < table.getRows().getCount(); i++) {
            //Set row height
            table.getRows().get(i).setHeight(20f);
            for (Object cell:table.getRows().get(i).getCells()){
                if (cell instanceof TableCell)
                {
                    //Set cell alignment
                    ((TableCell) cell).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                }
            }
        }

        //Set table alignment
        table.getTableFormat().setHorizontalAlignment(RowAlignment.Center);

        //Protect the document so that users can only fill out the form fields
        doc.protect(ProtectionType.Allow_Only_Form_Fields, "password");

        //Save the result document
        doc.saveToFile("AddFormFields.docx", FileFormat.Docx_2013);
    }
}

Выход:

Оригинал: “https://dev.to/eiceblue/create-form-fields-in-word-in-java-aga”