메이븐으로 설치

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

관련된 링크들

Word 문서의 변수는 텍스트 교체, 삭제 등 편리하고 정확한 텍스트 관리 기능이 특징인 필드 유형입니다. 찾기 및 바꾸기 기능과 비교하여 변수에 값을 할당하여 텍스트를 바꾸는 것이 더 빠르고 오류 발생 가능성이 적습니다. 이 기사에서는 방법을 보여 드리겠습니다 Word 문서에서 변수 추가 또는 변경 Spire.Doc for Java 사용하여 프로그래밍 방식으로.

Spire.Doc for Java 설치

먼저 Spire.Doc.jar 파일을 Java 프로그램의 종속성으로 추가해야 합니다. JAR 파일은 이 링크에서 다운로드할 수 있습니다. Maven을 사용하는 경우 프로젝트의 pom.xml 파일에 다음 코드를 추가하여 애플리케이션에서 JAR 파일을 쉽게 가져올 수 있습니다.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Word 문서에 변수 삽입

변수는 일종의 Word 필드이므로 Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) 메서드를 사용하여 Word 문서에 변수를 삽입한 다음 VariableCollection.add() 메서드를 사용하여 변수에 값을 할당할 수 있습니다. 변수에 값을 할당한 후 문서 필드를 업데이트하여 할당된 값을 표시해야 한다는 점에 유의해야 합니다. 자세한 단계는 다음과 같습니다.

  • Document 객체를 생성합니다.
  • Document.addSection() 메서드를 사용하여 문서에 섹션을 추가합니다.
  • Section.addParagraph() 메서드를 사용하여 섹션에 단락을 추가합니다.
  • Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) 메서드를 사용하여 단락에 변수 필드를 추가합니다.
  • Document.getVariables() 메소드를 사용하여 변수 컬렉션을 가져옵니다.
  • VariableCollection.add() 메서드를 사용하여 변수에 값을 할당합니다.
  • Document.isUpdateFields() 메서드를 사용하여 문서의 필드를 업데이트합니다.
  • Document.saveToFile() 메서드를 사용하여 문서를 저장합니다.
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.Paragraph;
    import com.spire.doc.formatting.CharacterFormat;
    
    public class AddVariables {
        public static void main(String[] args) {
    
            //Create an object of Document
            Document document = new Document();
    
            //Add a section
            Section section = document.addSection();
    
            //Add a paragraph
            Paragraph paragraph = section.addParagraph();
    
            //Set text format
            CharacterFormat characterFormat = paragraph.getStyle().getCharacterFormat();
            characterFormat.setFontName("Times New Roman");
            characterFormat.setFontSize(14);
    
            //Set the page margin
            section.getPageSetup().getMargins().setTop(80f);
    
            //Add variable fields to the paragraph
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" is an object.\r\n");
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" is not a backdrop, an illusion, or an emergent phenomenon.\r\n");
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" has a physical size that be measured in laboratories.");
    
            //Get the variable collection
            VariableCollection variableCollection = document.getVariables();
    
            //Assign a value to the variable
            variableCollection.add("Term", "Time");
    
            //Update the fields in the document
            document.isUpdateFields(true);
    
            //Save the document
            document.saveToFile("AddVariables.docx", FileFormat.Auto);
            document.dispose();
        }
    }

Java: Add and Change Variables in Word Documents

Word 문서에서 변수 값 변경

Spire.Doc for Java 변수 값을 변경하는 VariableCollection.set() 메소드를 제공합니다. 그리고 문서의 필드를 업데이트한 후 발생하는 모든 변수에 새로 할당된 값이 표시되므로 빠르고 정확한 텍스트 교체가 가능합니다. 자세한 단계는 다음과 같습니다.

  • Document 객체를 생성합니다..
  • Document.loaFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.getVariables() 메소드를 사용하여 변수 컬렉션을 가져옵니다.
  • VariableCollection.set() 메서드를 사용하여 이름을 통해 특정 변수에 새 값을 할당합니다.
  • Document.isUpdateFields() 메서드를 사용하여 문서의 필드를 업데이트합니다.
  • Document.saveToFile() 메서드를 사용하여 문서를 저장합니다.
  • Java
import com.spire.doc.Document;
    import com.spire.doc.FileFormat;
    import com.spire.doc.VariableCollection;
    
    public class ChangeVariableValue {
        public static void main(String[] args) {
    
            //Create an object of Document
            Document document = new Document();
    
            //Load a Word document
            document.loadFromFile("AddVariables.docx");
    
            //Get the variable collection
            VariableCollection variableCollection = document.getVariables();
    
            //Assign a new value to a variable
            variableCollection.set("Term", "The time");
    
            //Update the fields in the document
            document.isUpdateFields(true);
    
            //Save the document
            document.saveToFile("ChangeVariable.docx", FileFormat.Auto);
            document.dispose();
        }
    }

Java: Add and Change Variables in Word Documents

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Installa con Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Link correlati

Le variabili nei documenti di Word sono un tipo di campo caratterizzato dalla capacità di una gestione del testo comoda e accurata, come la sostituzione e l'eliminazione del testo. Rispetto alla funzione trova e sostituisci, la sostituzione del testo assegnando valori alle variabili è più veloce e meno soggetta a errori. Questo articolo mostrerà come farlo aggiungere o modificare variabili nei documenti Word in modo programmatico utilizzando Spire.Doc for Java.

Installa Spire.Doc for Java

Innanzitutto, devi aggiungere il file Spire.Doc.jar come dipendenza nel tuo programma Java. Il file JAR può essere scaricato da questo collegamento. Se utilizzi Maven, puoi importare facilmente il file JAR nella tua applicazione aggiungendo il seguente codice al file pom.xml del tuo progetto.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Inserisci variabili nei documenti di Word

Poiché le variabili sono una sorta di campi di Word, possiamo utilizzare il metodo Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) per inserire variabili nei documenti di Word, quindi utilizzare il metodo VariableCollection.add() per assegnare valori alle variabili. Va notato che dopo aver assegnato valori alle variabili, i campi del documento devono essere aggiornati per visualizzare i valori assegnati. I passaggi dettagliati sono i seguenti.

  • Creare un oggetto di Document.
  • Aggiungi una sezione al documento utilizzando il metodo Document.addSection().
  • Aggiungi un paragrafo alla sezione utilizzando il metodo Sezione.addParagraph().
  • Aggiungi campi variabili al paragrafo utilizzando il metodo Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable).
  • Ottieni la raccolta di variabili utilizzando il metodo Document.getVariables().
  • Assegna un valore alla variabile utilizzando il metodo VariableCollection.add().
  • Aggiorna i campi nel documento utilizzando il metodo Document.isUpdateFields().
  • Salvare il documento utilizzando il metodo Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.Paragraph;
    import com.spire.doc.formatting.CharacterFormat;
    
    public class AddVariables {
        public static void main(String[] args) {
    
            //Create an object of Document
            Document document = new Document();
    
            //Add a section
            Section section = document.addSection();
    
            //Add a paragraph
            Paragraph paragraph = section.addParagraph();
    
            //Set text format
            CharacterFormat characterFormat = paragraph.getStyle().getCharacterFormat();
            characterFormat.setFontName("Times New Roman");
            characterFormat.setFontSize(14);
    
            //Set the page margin
            section.getPageSetup().getMargins().setTop(80f);
    
            //Add variable fields to the paragraph
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" is an object.\r\n");
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" is not a backdrop, an illusion, or an emergent phenomenon.\r\n");
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" has a physical size that be measured in laboratories.");
    
            //Get the variable collection
            VariableCollection variableCollection = document.getVariables();
    
            //Assign a value to the variable
            variableCollection.add("Term", "Time");
    
            //Update the fields in the document
            document.isUpdateFields(true);
    
            //Save the document
            document.saveToFile("AddVariables.docx", FileFormat.Auto);
            document.dispose();
        }
    }

Java: Add and Change Variables in Word Documents

Modificare il valore delle variabili nei documenti di Word

Spire.Doc for Java fornisce il metodo VariableCollection.set() per modificare i valori delle variabili. E dopo aver aggiornato i campi nel documento, tutte le occorrenze delle variabili visualizzeranno il valore appena assegnato, ottenendo così una sostituzione del testo rapida e accurata. I passaggi dettagliati sono i seguenti.

  • Creare un oggetto di Document.
  • Carica un documento Word utilizzando il metodo Document.loaFromFile().
  • Ottieni la raccolta di variabili utilizzando il metodo Document.getVariables().
  • Assegna un nuovo valore a una variabile specifica tramite il suo nome utilizzando il metodo VariableCollection.set().
  • Aggiorna i campi nel documento utilizzando il metodo Document.isUpdateFields().
  • Salvare il documento utilizzando il metodo Document.saveToFile().
  • Java
import com.spire.doc.Document;
    import com.spire.doc.FileFormat;
    import com.spire.doc.VariableCollection;
    
    public class ChangeVariableValue {
        public static void main(String[] args) {
    
            //Create an object of Document
            Document document = new Document();
    
            //Load a Word document
            document.loadFromFile("AddVariables.docx");
    
            //Get the variable collection
            VariableCollection variableCollection = document.getVariables();
    
            //Assign a new value to a variable
            variableCollection.set("Term", "The time");
    
            //Update the fields in the document
            document.isUpdateFields(true);
    
            //Save the document
            document.saveToFile("ChangeVariable.docx", FileFormat.Auto);
            document.dispose();
        }
    }

Java: Add and Change Variables in Word Documents

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Installer avec Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Les variables dans les documents Word sont un type de champ caractérisé par la capacité de gestion de texte pratique et précise, comme le remplacement et la suppression de texte. Par rapport à la fonction Rechercher et remplacer, le remplacement du texte en attribuant des valeurs aux variables est plus rapide et moins sujet aux erreurs. Cet article va montrer comment ajouter ou modifier des variables dans des documents Word par programmation en utilisant Spire.Doc for Java.

Installer Spire.Doc for Java

Tout d'abord, vous devez ajouter le fichier Spire.Doc.jar en tant que dépendance dans votre programme Java. Le fichier JAR peut être téléchargé à partir de ce lien. Si vous utilisez Maven, vous pouvez facilement importer le fichier JAR dans votre application en ajoutant le code suivant au fichier pom.xml de votre projet.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Insérer des variables dans des documents Word

Comme les variables sont une sorte de champs Word, nous pouvons utiliser la méthode Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) pour insérer des variables dans des documents Word, puis utiliser la méthode VariableCollection.add() pour attribuer des valeurs aux variables. Il convient de noter qu'après avoir attribué des valeurs aux variables, les champs du document doivent être mis à jour pour afficher les valeurs attribuées. Les étapes détaillées sont les suivantes.

  • Créez un objet de Document.
  • Ajoutez une section au document à l'aide de la méthode Document.addSection().
  • Ajoutez un paragraphe à la section à l’aide de la méthode Section.addParagraph().
  • Ajoutez des champs variables au paragraphe à l’aide de la méthode Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable).
  • Obtenez la collection de variables à l’aide de la méthode Document.getVariables().
  • Attribuez une valeur à la variable à l’aide de la méthode VariableCollection.add().
  • Mettez à jour les champs du document à l'aide de la méthode Document.isUpdateFields().
  • Enregistrez le document à l'aide de la méthode Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.Paragraph;
    import com.spire.doc.formatting.CharacterFormat;
    
    public class AddVariables {
        public static void main(String[] args) {
    
            //Create an object of Document
            Document document = new Document();
    
            //Add a section
            Section section = document.addSection();
    
            //Add a paragraph
            Paragraph paragraph = section.addParagraph();
    
            //Set text format
            CharacterFormat characterFormat = paragraph.getStyle().getCharacterFormat();
            characterFormat.setFontName("Times New Roman");
            characterFormat.setFontSize(14);
    
            //Set the page margin
            section.getPageSetup().getMargins().setTop(80f);
    
            //Add variable fields to the paragraph
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" is an object.\r\n");
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" is not a backdrop, an illusion, or an emergent phenomenon.\r\n");
            paragraph.appendField("Term", FieldType.Field_Doc_Variable);
            paragraph.appendText(" has a physical size that be measured in laboratories.");
    
            //Get the variable collection
            VariableCollection variableCollection = document.getVariables();
    
            //Assign a value to the variable
            variableCollection.add("Term", "Time");
    
            //Update the fields in the document
            document.isUpdateFields(true);
    
            //Save the document
            document.saveToFile("AddVariables.docx", FileFormat.Auto);
            document.dispose();
        }
    }

Java: Add and Change Variables in Word Documents

Modifier la valeur des variables dans les documents Word

Spire.Doc for Java fournit la méthode VariableCollection.set() pour modifier les valeurs des variables. Et après la mise à jour des champs du document, toutes les occurrences des variables afficheront la valeur nouvellement attribuée, permettant ainsi un remplacement de texte rapide et précis. Les étapes détaillées sont les suivantes.

  • Créez un objet de Document.
  • Chargez un document Word à l'aide de la méthode Document.loaFromFile().
  • Obtenez la collection de variables à l’aide de la méthode Document.getVariables().
  • Attribuez une nouvelle valeur à une variable spécifique via son nom à l'aide de la méthode VariableCollection.set().
  • Mettez à jour les champs du document à l'aide de la méthode Document.isUpdateFields().
  • Enregistrez le document à l'aide de la méthode Document.saveToFile().
  • Java
import com.spire.doc.Document;
    import com.spire.doc.FileFormat;
    import com.spire.doc.VariableCollection;
    
    public class ChangeVariableValue {
        public static void main(String[] args) {
    
            //Create an object of Document
            Document document = new Document();
    
            //Load a Word document
            document.loadFromFile("AddVariables.docx");
    
            //Get the variable collection
            VariableCollection variableCollection = document.getVariables();
    
            //Assign a new value to a variable
            variableCollection.set("Term", "The time");
    
            //Update the fields in the document
            document.isUpdateFields(true);
    
            //Save the document
            document.saveToFile("ChangeVariable.docx", FileFormat.Auto);
            document.dispose();
        }
    }

Java: Add and Change Variables in Word Documents

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 06 November 2023 09:45

Java Create a Fillable Form in Word

Install with Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Related Links

Word allows you to create forms that other people can use to enter information. Fillable forms are used for a variety of purposes. Human resources use forms to collect employee and consultant information. Marketing departments use forms to survey customer satisfaction with their products and services. Organizations use forms to register members, students, or clients. Some of the tools you will use when creating a form include:

  • Content Controls: The areas where users input information in a form.
  • Tables: Tables are used in forms to align text and form fields, and to create borders and boxes.
  • Protection: Allows users to populate fields but not to make changes to the rest of the document.

Content controls in Word are containers for content that let users build structured documents. A structured document controls where content appears within the document. There are basically ten types of content controls available in Word 2013. This article focuses on how to create a fillable form in Word consisting of the following seven common content controls using Spire.Doc for Java.

Content Control Description
Plain Text A text field limited to plain text, so no formatting can be included.
Rich Text A text field that can contain formatted text or other items, such as tables, pictures, or other content controls.
Picture Accepts a single picture.
Drop-Down List A drop-down list displays a predefined list of items for the user to choose from.
Combo Box A combo box enables users to select a predefined value in a list or type their own value in the text box of the control.
Check Box A check box provides a graphical widget that allows the user to make a binary choice: yes (checked) or no (not checked).
Date Picker Contains a calendar control from which the user can select a date.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Create a Fillable Form in Word in Java

The StructureDocumentTagInline class provided by Spire.Doc for Java is used to create structured document tags for inline-level structures (DrawingML object, fields, etc.) in a paragraph. The SDTProperties property and the SDTContent property under this class shall be used to specify the properties and content of the current structured document tag. The following are the detailed steps to create a fillable form with content controls in Word.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Add a table using Section.addTable() method.
  • Add a paragraph to a specific table cell using TableCell.addParagraph() method.
  • Create an instance of StructureDocumentTagInline class, and add it to the paragraph as a child object using Paragraph.getChildObjects().add() method.
  • Specify the properties and content of the structured document tag using the methods under the SDTProperties property and the SDTContent property of the StructureDocumentTagInline object. The type of the structured document tag is set through SDTProperties.setSDTType() method.
  • Prevent users from editing content outside form fields using Document.protect() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Instalar com Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Links Relacionados

O Word permite criar formulários que outras pessoas podem usar para inserir informações. Formulários preenchíveis são usados para diversos fins. Os recursos humanos utilizam formulários para coletar informações de funcionários e consultores. Os departamentos de marketing usam formulários para pesquisar a satisfação do cliente com seus produtos e serviços. As organizações usam formulários para registrar membros, estudantes ou clientes. Algumas das ferramentas que você usará ao criar um formulário incluem:

  • Controles de conteúdo: as áreas onde os usuários inserem informações em um formulário.
  • Tabelas:As tabelas são usadas em formulários para alinhar texto e campos de formulário e para criar bordas e caixas.
  • Proteção: permite que os usuários preencham os campos, mas não façam alterações no restante do documento.

Os controles de conteúdo no Word são contêineres de conteúdo que permitem aos usuários criar documentos estruturados.Um documento estruturado controla onde o conteúdo aparece no documento. Existem basicamente dez tipos de controles de conteúdo disponíveis no Word 2013. Este artigo se concentra em como crie um formulário preenchível no Word consistindo nos sete controles de conteúdo comuns a seguir usando Spire.Doc for Java.

Controle de conteúdo Descrição
Texto simples Um campo de texto limitado a texto simples, portanto nenhuma formatação pode ser incluída.
Texto rico Um campo de texto que pode conter texto formatado ou outros itens, como tabelas, imagens ou outros controles de conteúdo.
Foto Aceita uma única foto.
Lista suspensa Uma lista suspensa exibe uma lista predefinida de itens para o usuário escolher.
Caixa combo Uma caixa de combinação permite aos usuários selecionar um valor predefinido em uma lista ou digitar seu próprio valor na caixa de texto do controle.
Caixa de seleção Uma caixa de seleção fornece um widget gráfico que permite ao usuário fazer uma escolha binária: sim (marcado) ou não (não marcado).
Seletor de data Contém um controle de calendário no qual o usuário pode selecionar uma data.

Instale Spire.Doc for Java

Primeiro de tudo, você deve adicionar o arquivo Spire.Doc.jar como uma dependência em seu programa Java. O arquivo JAR pode ser baixado neste link. Se você usa Maven, pode importar facilmente o arquivo JAR em seu aplicativo adicionando o código a seguir ao arquivo pom.xml do seu projeto.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Crie um formulário preenchível no Word em Java

A classe StructureDocumentTagInline fornecida por Spire.Doc para Java é usada para criar tags de documentos estruturados para estruturas de nível embutido (objeto DrawingML, campos, etc.) em um parágrafo. A propriedade SDTProperties e a propriedade SDTContent nesta classe devem ser usadas para especificar as propriedades e o conteúdo da tag do documento estruturado atual. A seguir estão as etapas detalhadas para criar um formulário preenchível com controles de conteúdo no Word.

  • Crie um objeto Documento.
  • Adicione uma seção usando o método Document.addSection().
  • Adicione uma tabela usando o método Section.addTable().
  • Adicione um parágrafo a uma célula específica da tabela usando o método TableCell.addParagraph().
  • Crie uma instância da classe StructureDocumentTagInline e adicione-a ao parágrafo como um objeto filho usando o método Paragraph.getChildObjects().add().
  • Especifique as propriedades e o conteúdo da tag de documento estruturado usando os métodos na propriedade SDTProperties e na propriedade SDTContent do objeto StructureDocumentTagInline. O tipo da tag do documento estruturado é definido por meio do método SDTProperties.setSDTType().
  • Evite que os usuários editem conteúdo fora dos campos do formulário usando o método Document.protect().
  • Salve o documento usando o método Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Установить с помощью Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
    </dependency>
    

Ссылки по теме

Word позволяет создавать формы, которые другие люди могут использовать для ввода информации. Заполняемые формы используются для различных целей. Отдел кадров использует формы для сбора информации о сотрудниках и консультантах. Отделы маркетинга используют формы для опроса удовлетворенности клиентов их продуктами и услугами. Организации используют формы для регистрации членов, студентов или клиентов. Некоторые из инструментов, которые вы будете использовать при создании формы, включают:

  • Элементы управления содержимым: области, в которых пользователи вводят информацию в форму.
  • Таблицы:Таблицы используются в формах для выравнивания текста и полей формы, а также для создания границ и полей.
  • Защита: позволяет пользователям заполнять поля, но не вносить изменения в остальную часть документа.

Элементы управления содержимым в Word — это контейнеры для содержимого, которые позволяют пользователям создавать структурированные документы. Структурированный документ определяет, где в документе отображается содержимое. В Word 2013 доступно десять типов элементов управления содержимым. В этой статье основное внимание уделяется тому, как создать заполняемую форму в Word состоящий из следующих семи общих элементов управления содержимым, использующих Spire.Doc for Java.

Контроль контента Описание
Простой текст Текстовое поле, ограниченное обычным текстом, поэтому форматирование невозможно.
Богатый текст Текстовое поле, которое может содержать форматированный текст или другие элементы, например таблицы, изображения или другие элементы управления содержимым.
Картина Принимает одно изображение.
Выпадающий список В раскрывающемся списке отображается заранее определенный список элементов, из которых пользователь может выбирать.
Поле со списком Поле со списком позволяет пользователям выбирать предопределенное значение в списке или вводить собственное значение в текстовое поле элемента управления.
Флажок Флажок представляет собой графический виджет, который позволяет пользователю сделать двоичный выбор: да (отмечено) или нет (не отмечено).
Выбор даты Содержит элемент управления календарем, из которого пользователь может выбрать дату.

Установите Spire.Doc for Java

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

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Создайте заполняемую форму в Word на Java

Класс StructureDocumentTagInline, предоставляемый Spire.Doc для Java, используется для создания тегов структурированного документа для структур строкового уровня (объекта DrawingML, полей и т. д.) в абзаце. Свойство SDTProperties и свойство SDTContent этого класса должны использоваться для указания свойств и содержимого текущего тега структурированного документа. Ниже приведены подробные инструкции по созданию заполняемой формы с элементами управления содержимым в Word.

  • Создайте объект Документ.
  • Добавьте раздел, используя метод Document.addSection().
  • Добавьте таблицу с помощью метода Раздел.addTable().
  • Добавьте абзац в определенную ячейку таблицы с помощью метода TableCell.addParagraph().
  • Создайте экземпляр класса StructureDocumentTagInline и добавьте его в абзац как дочерний объект с помощью метода Paragraph.getChildObjects().add().
  • Укажите свойства и содержимое тега структурированного документа, используя методы свойства SDTProperties и свойства SDTContent объекта StructureDocumentTagInline. Тип тега структурированного документа задается с помощью метода SDTProperties.setSDTType().
  • Запретите пользователям редактировать содержимое вне полей формы с помощью метода Document.protect().
  • Сохраните документ, используя метод Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста, запросите 30-дневную пробную лицензию для себя.

Смотрите также

Mit Maven installieren

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

verwandte Links

Mit Word können Sie Formulare erstellen, mit denen andere Personen Informationen eingeben können. Ausfüllbare Formulare werden für verschiedene Zwecke verwendet. Die Personalabteilung verwendet Formulare, um Mitarbeiter- und Beraterinformationen zu sammeln. Marketingabteilungen nutzen Formulare, um die Kundenzufriedenheit mit ihren Produkten und Dienstleistungen zu erheben. Organisationen verwenden Formulare, um Mitglieder, Studenten oder Kunden zu registrieren. Zu den Tools, die Sie beim Erstellen eines Formulars verwenden, gehören:

  • Inhaltssteuerelemente: Die Bereiche, in denen Benutzer Informationen in ein Formular eingeben.
  • Tabellen: Tabellen werden in Formularen verwendet, um Text und Formularfelder auszurichten sowie Rahmen und Felder zu erstellen.
  • Schutz: Ermöglicht Benutzern das Ausfüllen von Feldern, jedoch keine Änderungen am Rest des Dokuments.

Inhaltssteuerelemente in Word sind Container für Inhalte, mit denen Benutzer strukturierte Dokumenteerstellen können. Ein strukturiertes Dokument steuert, wo Inhalte im Dokument angezeigt werden. Grundsätzlich stehen in Word 2013 zehn Arten von Inhaltssteuerelementen zur Verfügung. Dieser Artikel konzentriert sich auf die Vorgehensweise Erstellen Sie ein ausfüllbares Formular in Word bestehend aus den folgenden sieben allgemeinen Inhaltssteuerelementen unter Verwendung von Spire.Doc for Java.

Inhaltskontrolle Beschreibung
Klartext Ein Textfeld, das auf reinen Text beschränkt ist und daher keine Formatierung enthalten kann.
Rich-Text Ein Textfeld, das formatierten Text oder andere Elemente wie Tabellen, Bilder oder andere Inhaltssteuerelemente enthalten kann.
Bild Akzeptiert ein einzelnes Bild.
Dropdown-Liste Eine Dropdown-Liste zeigt eine vordefinierte Liste von Elementen an, aus denen der Benutzer auswählen kann.
Kombinationsfeld Über ein Kombinationsfeld können Benutzer einen vordefinierten Wert aus einer Liste auswählen oder einen eigenen Wert in das Textfeld des Steuerelements eingeben.
Kontrollkästchen Ein Kontrollkästchen stellt ein grafisches Widget bereit, mit dem der Benutzer eine binäre Auswahl treffen kann: Ja (aktiviert) oder Nein (nicht aktiviert).
Datumsauswahl Enthält ein Kalendersteuerelement, aus dem der Benutzer ein Datum auswählen kann.

Installieren Sie Spire.Doc for Java

Zunächst müssen Sie die Datei Spire.Doc.jar als Abhängigkeit zu Ihrem Java-Programm hinzufügen. Die JAR-Datei kann über diesen Link heruntergeladen werden. Wenn Sie Maven verwenden, können Sie die JAR-Datei einfach in Ihre Anwendung importieren, indem Sie den folgenden Code zur pom.xml-Datei Ihres Projekts hinzufügen.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Erstellen Sie ein ausfüllbares Formular in Word in Java

Die von Spire.Doc for Java bereitgestellte StructureDocumentTagInline-Klasse wird zum Erstellen strukturierter Dokument-Tags für Strukturen auf Inline-Ebene (DrawingML-Objekt, Felder usw.) in einem Absatz verwendet. Die SDTProperties-Eigenschaft und die SDTContent-Eigenschaft dieser Klasse werden verwendet, um die Eigenschaften und den Inhalt des aktuellen strukturierten Dokument-Tags anzugeben. Im Folgenden finden Sie die detaillierten Schritte zum Erstellen eines ausfüllbaren Formulars mit Inhaltssteuerelementen in Word.

  • Erstellen Sie ein Document-Objekt.
  • Fügen Sie einen Abschnitt mit der Methode Document.addSection() hinzu.
  • Fügen Sie eine Tabelle mit der Methode Section.addTable() hinzu.
  • Fügen Sie mit der Methode TableCell.addParagraph() einen Absatz zu einer bestimmten Tabellenzelle hinzu.
  • Erstellen Sie eine Instanz der StructureDocumentTagInline-Klasse und fügen Sie sie mit der Methode Paragraph.getChildObjects().add() als untergeordnetes Objekt zum Absatz hinzu.
  • Geben Sie die Eigenschaften und den Inhalt des strukturierten Dokumenttags mithilfe der Methoden unter der SDTProperties-Eigenschaft und der SDTContent-Eigenschaft des StructureDocumentTagInline-Objekts an. Der Typ des strukturierten Dokument-Tags wird über die Methode SDTProperties.setSDTType() festgelegt.
  • Verhindern Sie, dass Benutzer Inhalte außerhalb von Formularfeldern bearbeiten, indem Sie die Methode Document.protect() verwenden.
  • Speichern Sie das Dokument mit der Methode Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Monday, 06 November 2023 09:40

Java Crear un formulario rellenable en Word

Instalar con Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

enlaces relacionados

Word le permite crear formularios que otras personas pueden usar para ingresar información. Los formularios rellenables se utilizan para diversos fines. Recursos humanos utiliza formularios para recopilar información de empleados y consultores. Los departamentos de marketing utilizan formularios para encuestar la satisfacción del cliente con sus productos y servicios. Las organizaciones utilizan formularios para registrar miembros, estudiantes o clientes. Algunas de las herramientas que utilizará al crear un formulario incluyen:

  • Controles de contenido:las áreas donde los usuarios ingresan información en un formulario.
  • Tablas: las tablas se utilizan en formularios para alinear texto y campos de formulario, y para crear bordes y cuadros.
  • Protección: permite a los usuarios completar campos pero no realizar cambios en el resto del documento.

Los controles de contenido en Word son contenedores de contenido que permiten a los usuarios crear documentos estructurados.Un documento estructurado controla dónde aparece el contenido dentro del documento. Básicamente, existen diez tipos de controles de contenido disponibles en Word 2013. Este artículo se centra en cómo crear un formulario rellenable en Word que consta de los siguientes siete controles de contenido comunes que utilizan Spire.Doc for Java.

Control de contenido Descripción
Texto sin formato Un campo de texto limitado a texto sin formato, por lo que no se puede incluir formato.
Texto rico Un campo de texto que puede contener texto formateado u otros elementos, como tablas, imágenes u otros controles de contenido.
Imagen Acepta una sola imagen.
La lista desplegable Una lista desplegable muestra una lista predefinida de elementos para que el usuario elija.
Caja combo Un cuadro combinado permite a los usuarios seleccionar un valor predefinido en una lista o escribir su propio valor en el cuadro de texto del control.
Casilla de verificación Una casilla de verificación proporciona un widget gráfico que permite al usuario realizar una elección binaria: sí (marcado) o no (no marcado).
Selector de fechas Contiene un control de calendario desde el cual el usuario puede seleccionar una fecha.

Instalar Spire.Doc for Java

En primer lugar, debe agregar el archivo Spire.Doc.jar como una dependencia en su programa Java. El archivo JAR se puede descargar desde este enlace.Si usa Maven, puede importar fácilmente el archivo JAR en su aplicación agregando el siguiente código al archivo pom.xml de su proyecto.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Crear un formulario rellenable en Word en Java

La clase StructureDocumentTagInline proporcionada por Spire.Doc para Java se utiliza para crear etiquetas de documentos estructurados para estructuras de nivel en línea (objeto DrawingML, campos, etc.) en un párrafo. La propiedad SDTProperties y la propiedad SDTContent de esta clase se utilizarán para especificar las propiedades y el contenido de la etiqueta del documento estructurado actual. Los siguientes son los pasos detallados para crear un formulario rellenable con controles de contenido en Word.

  • Crea un objeto de documento.
  • Agregue una sección usando el método Document.addSection().
  • Agregue una tabla usando el método Sección.addTable().
  • Agregue un párrafo a una celda de tabla específica usando el método TableCell.addParagraph().
  • Cree una instancia de la clase StructureDocumentTagInline y agréguela al párrafo como un objeto secundario utilizando el método Paragraph.getChildObjects().add().
  • Especifique las propiedades y el contenido de la etiqueta del documento estructurado utilizando los métodos de la propiedad SDTProperties y la propiedad SDTContent del objeto StructureDocumentTagInline. El tipo de etiqueta de documento estructurado se establece mediante el método DTProperties.setSDTType()S.
  • Evite que los usuarios editen contenido fuera de los campos del formulario utilizando el método Document.protect().
  • Guarde el documento utilizando el método Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

Solicite una licencia temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

메이븐으로 설치

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

관련된 링크들

Word를 사용하면 다른 사람이 정보를 입력하는 데 사용할 수 있는 양식을 만들 수 있습니다. 채울 수 있는 양식은 다양한 목적으로 사용됩니다. 인사부에서는 양식을 사용하여 직원 및 컨설턴트 정보를 수집합니다. 마케팅 부서에서는 양식을 사용하여 제품 및 서비스에 대한 고객 만족도를 조사합니다. 조직에서는 양식을 사용하여 회원, 학생 또는 고객을 등록합니다. 양식을 만들 때 사용할 도구 중 일부는 다음과 같습니다.

  • 콘텐츠 컨트롤: 사용자가 양식에 정보를 입력하는 영역입니다.
  • 테이블: 테이블은 양식에서 텍스트와 양식 필드를 정렬하고 테두리와 상자를 만드는 데 사용됩니다.
  • 보호: 사용자가 필드를 채울 수 있지만 문서의 나머지 부분을 변경할 수는 없습니다.

Word의 콘텐츠 컨트롤은 사용자가 구조화된 문서를 작성할 수 있는 콘텐츠의 컨테이너입니다. 구조화된 문서는 문서 내에서 콘텐츠가 표시되는 위치를 제어합니다. Word 2013에서는 기본적으로 10가지 유형의 콘텐츠 컨트롤을 사용할 수 있습니다. 이 문서에서는 Word에서 채울 수 있는 양식 만들기 Spire.Doc for Java사용하는 다음 7가지 공통 콘텐츠 컨트롤로 구성됩니다.

콘텐츠 제어 설명
일반 텍스트 텍스트 필드는 일반 텍스트로 제한되므로 서식을 포함할 수 없습니다.
리치 텍스트 서식이 지정된 텍스트나 표, 그림, 기타 콘텐츠 컨트롤과 같은 기타 항목을 포함할 수 있는 텍스트 필드입니다.
그림 단일 사진을 허용합니다.
드롭 다운 목록 드롭다운 목록에는 사용자가 선택할 수 있는 미리 정의된 항목 목록이 표시됩니다.
콤보 박스 콤보 상자를 사용하면 사용자는 목록에서 미리 정의된 값을 선택하거나 컨트롤의 텍스트 상자에 자신의 값을 입력할 수 있습니다.
체크박스 확인란은 사용자가 예(선택됨) 또는 아니오(선택 안함)라는 이진 선택을 할 수 있는 그래픽 위젯을 제공합니다.
날짜 선택기 사용자가 날짜를 선택할 수 있는 달력 컨트롤을 포함합니다.

Spire.Doc for Java 설치

우선, Spire.Doc.jar 파일을 Java 프로그램의 종속성으로 추가해야 합니다. JAR 파일은 이 링크에서 다운로드할 수 있습니다. Maven을 사용하는 경우 프로젝트의 pom.xml 파일에 다음 코드를 추가하여 애플리케이션에서 JAR 파일을 쉽게 가져올 수 있습니다.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Java의 Word에서 채울 수 있는 양식 만들기

Spire.Doc for Java에서 제공하는 StructureDocumentTagInline 클래스는 단락의 인라인 수준 구조(드로잉ML 개체, 필드 등)에 대한 구조화된 문서 태그를 만드는 데 사용됩니다. 이 클래스 아래의 SDTProperties 속성과 SDTContent 속성은 현재 구조화된 문서 태그의 속성과 내용을 지정하는 데 사용됩니다. 다음은 Word에서 콘텐츠 컨트롤을 사용하여 채울 수 있는 양식을 만드는 자세한 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.addSection() 메서드를 사용하여 섹션을 추가합니다.
  • Section.addTable() 메서드를 사용하여 테이블을 추가합니다.
  • TableCell.addParagraph() 메서드를 사용하여 특정 표 셀에 단락을 추가합니다.
  • StructureDocumentTagInline 클래스의 인스턴스를 생성하고 Paragraph.getChildObjects().add() 메서드를 사용하여 단락에 하위 객체로 추가합니다.
  • SDTProperties 속성 및 StructureDocumentTagInline 개체의 SDTContent 속성 아래에 있는 메서드를 사용하여 구조화된 문서 태그의 속성과 콘텐츠를 지정합니다. 구조화된 문서 태그의 유형은 SDTProperties.setSDTType() 메소드를 통해 설정됩니다.
  • Document.protect() 메서드를 사용하여 사용자가 양식 필드 외부의 콘텐츠를 편집하지 못하도록 합니다.
  • Document.saveToFile() 메서드를 사용하여 문서를 저장합니다.
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Monday, 06 November 2023 09:39

Java Crea un modulo compilabile in Word

Installa con Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Link correlati

Word ti consente di creare moduli che altre persone possono utilizzare per inserire informazioni. I moduli compilabili vengono utilizzati per diversi scopi. Le risorse umane utilizzano moduli per raccogliere informazioni su dipendenti e consulenti. I reparti marketing utilizzano moduli per sondare la soddisfazione dei clienti rispetto ai loro prodotti e servizi. Le organizzazioni utilizzano moduli per registrare membri, studenti o clienti. Alcuni degli strumenti che utilizzerai durante la creazione di un modulo includono:

  • Controlli del contenuto: aree in cui gli utenti inseriscono informazioni in un modulo.
  • Tabelle: le tabelle vengono utilizzate nei moduli per allineare testo e campi modulo e per creare bordi e caselle.
  • Protezione: consente agli utenti di compilare i campi ma non di apportare modifiche al resto del documento.

I controlli contenuto in Word sono contenitori di contenuto che consentono agli utenti di creare documenti strutturati.Un documento strutturato controlla dove appare il contenuto all'interno del documento. Esistono fondamentalmente dieci tipi di controlli del contenuto disponibili in Word 2013. Questo articolo si concentra su come farlo creare un modulo compilabile in Word costituito dai seguenti sette controlli di contenuto comuni che utilizzano Spire.Doc for Java.

Controllo dei contenuti Descrizione
Testo semplice Un campo di testo limitato al testo semplice, pertanto non è possibile includere alcuna formattazione.
Testo ricco Un campo di testo che può contenere testo formattato o altri elementi, come tabelle, immagini o altri controlli contenuto.
Immagine Accetta una singola immagine.
Menu `A tendina Un elenco a discesa visualizza un elenco predefinito di elementi tra cui l'utente può scegliere.
Casella combinata Una casella combinata consente agli utenti di selezionare un valore predefinito in un elenco o digitare il proprio valore nella casella di testo del controllo.
Casella di controllo Una casella di controllo fornisce un widget grafico che consente all'utente di effettuare una scelta binaria: sì (selezionato) o no (non selezionato).
Date picker Contiene un controllo del calendario da cui l'utente può selezionare una data.

Installa Spire.Doc for Java

Prima di tutto, devi aggiungere il file Spire.Doc.jar come dipendenza nel tuo programma Java. Il file JAR può essere scaricato da questo collegamento. Se utilizzi Maven, puoi importare facilmente il file JAR nella tua applicazione aggiungendo il seguente codice al file pom.xml del tuo progetto.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Crea un modulo compilabile in Word in Java

La classe StructureDocumentTagInline fornita da Spire.Doc per Java viene utilizzata per creare tag di documento strutturati per strutture a livello inline (oggetto DrawingML, campi, ecc.) in un paragrafo. La proprietà SDTProperties e la proprietà SDTContent in questa classe devono essere utilizzate per specificare le proprietà e il contenuto del tag del documento strutturato corrente. Di seguito sono riportati i passaggi dettagliati per creare un modulo compilabile con controlli del contenuto in Word.

  • Creare un oggetto Documento.
  • Aggiungi una sezione utilizzando il metodo Document.addSection().
  • Aggiungi una tabella utilizzando il metodo Sezione.addTable().
  • Aggiungi un paragrafo a una cella di tabella specifica utilizzando il metodo TableCell.addParagraph().
  • Crea un'istanza della classe StructureDocumentTagInline e aggiungila al paragrafo come oggetto figlio utilizzando il metodo Paragraph.getChildObjects().add().
  • Specificare le proprietà e il contenuto del tag del documento strutturato utilizzando i metodi nella proprietà SDTProperties e nella proprietà SDTContent dell'oggetto StructureDocumentTagInline. Il tipo del tag del documento strutturato viene impostato tramite il metodo SDTProperties.setSDTType().
  • Impedisci agli utenti di modificare il contenuto all'esterno dei campi del modulo utilizzando il metodo Document.protect().
  • Salvare il documento utilizzando il metodo Document.saveToFile().
  • Java
import com.spire.doc.*;
    import com.spire.doc.documents.*;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    import java.util.Date;
    
    public class CreateFillableForm {
    
        public static void main(String[] args) {
    
            //Create a Document object
            Document doc = new Document();
    
            //Add a section
            Section section = doc.addSection();
    
            //add a table
            Table table = section.addTable(true);
            table.resetCells(7, 2);
    
            //Add text to the cells of the first column
            Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
            paragraph.appendText("Plain Text Content Control");
            paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
            paragraph.appendText("Rich Text Content Control");
            paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
            paragraph.appendText("Picture Content Control");
            paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
            paragraph.appendText("Drop-Down List Content Control");
            paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
            paragraph.appendText("Check Box Content Control");
            paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
            paragraph.appendText("Combo box Content Control");
            paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
            paragraph.appendText("Date Picker Content Control");
    
            //Add a plain text content control to the cell (0,1)
            paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Text);
            sdt.getSDTProperties().setAlias("Plain Text");
            sdt.getSDTProperties().setTag("Plain Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            SdtText text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            TextRange tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a rich text content control to the cell (1,1)
            paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
            sdt.getSDTProperties().setAlias("Rich Text");
            sdt.getSDTProperties().setTag("Rich Text");
            sdt.getSDTProperties().isShowingPlaceHolder(true);
            text = new SdtText(true);
            text.isMultiline(false);
            sdt.getSDTProperties().setControlProperties(text);
            tr = new TextRange(doc);
            tr.setText("Click or tap here to enter text.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a picture content control to the cell (2,1)
            paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Picture);
            sdt.getSDTProperties().setAlias("Picture");
            sdt.getSDTProperties().setTag("Picture");
            SdtPicture sdtPicture = new SdtPicture();
            sdt.getSDTProperties().setControlProperties(sdtPicture);
            DocPicture pic = new DocPicture(doc);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
            sdt.getSDTContent().getChildObjects().add(pic);
    
            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
            sdt.getSDTProperties().setAlias("Dropdown List");
            sdt.getSDTProperties().setTag("Dropdown List");
            paragraph.getChildObjects().add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
            sddl.getListItems().add(new SdtListItem("Item 2", "2"));
            sddl.getListItems().add(new SdtListItem("Item 3", "3"));
            sddl.getListItems().add(new SdtListItem("Item 4", "4"));
            sdt.getSDTProperties().setControlProperties(sddl);
            tr = new TextRange(doc);
            tr.setText(sddl.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add two check box content controls to the cell (4,1)
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            SdtCheckBox scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 1");
    
            paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
            scb = new SdtCheckBox();
            sdt.getSDTProperties().setControlProperties(scb);
            tr = new TextRange(doc);
            sdt.getChildObjects().add(tr);
            scb.setChecked(false);
            paragraph.appendText(" Option 2");
    
            //Add a combo box content control to the cell (5,1)
            paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
            sdt.getSDTProperties().setAlias("Combo Box");
            sdt.getSDTProperties().setTag("Combo Box");
            SdtComboBox cb = new SdtComboBox();
            cb.getListItems().add(new SdtListItem("Choose an item."));
            cb.getListItems().add(new SdtListItem("Item 2"));
            cb.getListItems().add(new SdtListItem("Item 3"));
            sdt.getSDTProperties().setControlProperties(cb);
            tr = new TextRange(doc);
            tr.setText(cb.getListItems().get(0).getDisplayText());
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Add a date picker content control to the cell (6,1)
            paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.getChildObjects().add(sdt);
            sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
            sdt.getSDTProperties().setAlias("Date Picker");
            sdt.getSDTProperties().setTag("Date Picker");
            SdtDate date = new SdtDate();
            date.setCalendarType(CalendarType.Default);
            date.setDateFormat("yyyy.MM.dd");
            date.setFullDate(new Date());
            sdt.getSDTProperties().setControlProperties(date);
            tr = new TextRange(doc);
            tr.setText("Click or tap to enter a date.");
            sdt.getSDTContent().getChildObjects().add(tr);
    
            //Allow users to edit the form fields only
            doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
    
            //Save to file
            doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
        }
    }

Java: Create a Fillable Form in Word

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche