Install with Maven

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

Related Links

Variables in Word documents are a type of field that is characterized by the ability of convenient and accurate text management, such as text replacement and deletion. Compared with the find-and-replace function, replacing text by assigning values to variables is faster and less error-prone. This article is going to show how to add or change variables in Word documents programmatically using Spire.Doc for Java.

Install Spire.Doc for Java

First, 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>14.5.3</version>
    </dependency>
</dependencies>

Insert Variables into Word Documents

As variables are a kind of Word fields, we can use the Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) method to insert variables into Word documents, and then use the VariableCollection.add() method to assign values to the variables. It should be noted that after assigning values to variables, document fields need to be updated to display the assigned values. The detailed steps are as follows.

  • Create an object of Document.
  • Add a section to the document using Document.addSection() method.
  • Add a paragraph to the section using Section.addParagraph() method.
  • Add variable fields to the paragraph using Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) method.
  • Get the variable collection using Document.getVariables() method.
  • Assign a value to the variable using VariableCollection.add() method.
  • Update the fields in the document using Document.isUpdateFields() method.
  • Save the document using Document.saveToFile() method.
  • 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

Change the Value of Variables in Word Documents

Spire.Doc for Java provides the VariableCollection.set() method to change the values of variables. And after updating fields in the document, all the occurrences of the variables will display the newly assigned value, thus achieving fast and accurate text replacement. The detailed steps are as follows.

  • Create an object of Document.
  • Load a Word document using Document.loaFromFile() method.
  • Get the variable collection using Document.getVariables() method.
  • Assign a new value to a specific variable through its name using VariableCollection.set() method.
  • Update the fields in the document using Document.isUpdateFields() method.
  • Save the document using Document.saveToFile() method.
  • 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

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

Variáveis ​​em documentos do Word são um tipo de campo que se caracteriza pela capacidade de gerenciamento de texto conveniente e preciso, como substituição e exclusão de texto. Em comparação com a função localizar e substituir, substituir texto atribuindo valores a variáveis é mais rápido e menos sujeito a erros. Este artigo vai mostrar como adicione ou altere variáveis em documentos do Word programaticamente usando Spire.Doc for Java.

Instale Spire.Doc for Java

Primeiro, você precisa 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>14.5.3</version>
    </dependency>
</dependencies>

Inserir variáveis em documentos do Word

Como variáveis são um tipo de campo do Word, podemos usar o método Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) para inserir variáveis em documentos do Word e, em seguida, usar o método VariableCollection.add() para atribuir valores às variáveis. Deve-se observar que após atribuir valores às variáveis, os campos do documento precisam ser atualizados para exibir os valores atribuídos. As etapas detalhadas são as seguintes.

  • Crie um objeto de Document.
  • Adicione uma seção ao documento usando o método Document.addSection().
  • Adicione um parágrafo à seção usando o método Section.addParagraph().
  • Adicione campos variáveis ​​ao parágrafo usando o método Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable).
  • Obtenha a coleção de variáveis usando o método Document.getVariables().
  • Atribua um valor à variável usando o método VariableCollection.add().
  • Atualize os campos do documento usando o método Document.isUpdateFields().
  • Salve o documento usando o método 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

Alterar o valor das variáveis em documentos do Word

Spire.Doc for Java fornece o método VariableCollection.set() para alterar os valores das variáveis. E após a atualização dos campos do documento, todas as ocorrências das variáveis ​​irão exibir o valor recém-atribuído, conseguindo assim uma substituição de texto rápida e precisa. As etapas detalhadas são as seguintes.

  • Crie um objeto de Document.
  • Carregue um documento do Word usando o método Document.loaFromFile().
  • Obtenha a coleção de variáveis usando o método Document.getVariables().
  • Atribua um novo valor a uma variável específica através de seu nome usando o método VariableCollection.set().
  • Atualize os campos do documento usando o método Document.isUpdateFields().
  • Salve o documento usando o método 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

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

Mit Maven installieren

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

verwandte Links

Variablen in Word-Dokumenten sind ein Feldtyp, der sich durch die Möglichkeit einer bequemen und genauen Textverwaltung auszeichnet, beispielsweise durch Ersetzen und Löschen von Text. Im Vergleich zur Funktion „Suchen und Ersetzen“ ist das Ersetzen von Text durch Zuweisen von Werten zu Variablen schneller und weniger fehleranfällig. Dieser Artikel zeigt, wie es geht Variablen in Word-Dokumenten hinzufügen oder ändern programmgesteuert mit Spire.Doc for Java.

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>14.5.3</version>
    </dependency>
</dependencies>

Fügen Sie Variablen in Word-Dokumente ein

Da Variablen eine Art Word-Felder sind, können wir die Methode Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) verwenden, um Variablen in Word-Dokumente einzufügen, und dann die Methode VariableCollection.add() verwenden, um den Variablen Werte zuzuweisen. Es ist zu beachten, dass nach dem Zuweisen von Werten zu Variablen die Dokumentfelder aktualisiert werden müssen, um die zugewiesenen Werte anzuzeigen. Die detaillierten Schritte sind wie folgt.

  • Erstellen Sie ein Dokumentobjekt.
  • Fügen Sie dem Dokument mit der Methode Document.addSection() einen Abschnitt hinzu.
  • Fügen Sie dem Abschnitt mit der Methode Section.addParagraph() einen Absatz hinzu.
  • Fügen Sie dem Absatz mithilfe der Methode Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) variable Felder hinzu.
  • Rufen Sie die Variablensammlung mit der Methode Document.getVariables() ab.
  • Weisen Sie der Variablen mit der Methode VariableCollection.add() einen Wert zu.
  • Aktualisieren Sie die Felder im Dokument mit der Methode Document.isUpdateFields().
  • Speichern Sie das Dokument mit der Methode 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

Ändern Sie den Wert von Variablen in Word-Dokumenten

Spire.Doc for Java bietet die Methode VariableCollection.set() zum Ändern der Werte von Variablen. Und nach der Aktualisierung der Felder im Dokument zeigen alle Vorkommen der Variablen den neu zugewiesenen Wert an, wodurch eine schnelle und genaue Textersetzung erreicht wird. Die detaillierten Schritte sind wie folgt.

  • Erstellen Sie ein Dokumentobjekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.loaFromFile().
  • Rufen Sie die Variablensammlung mit der Methode Document.getVariables() ab.
  • Weisen Sie einer bestimmten Variablen über ihren Namen mit der Methode VariableCollection.set() einen neuen Wert zu.
  • Aktualisieren Sie die Felder im Dokument mit der Methode Document.isUpdateFields().
  • Speichern Sie das Dokument mit der Methode 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

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

Instalar con Maven

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

enlaces relacionados

Las variables en los documentos de Word son un tipo de campo que se caracteriza por la capacidad de administrar texto de manera conveniente y precisa, como el reemplazo y la eliminación de texto. En comparación con la función de buscar y reemplazar, reemplazar texto asignando valores a variables es más rápido y menos propenso a errores. Este artículo le mostrará cómo agregue o cambie variables en documentos de Word mediante programación usando Spire.Doc for Java.

Instalar Spire.Doc for Java

Primero, 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>14.5.3</version>
    </dependency>
</dependencies>

Insertar variables en documentos de Word

Como las variables son una especie de campos de Word, podemos usar el método Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) para insertar variables en documentos de Word y luego usar el método VariableCollection.add() para asignar valores a las variables. Cabe señalar que después de asignar valores a las variables, los campos del documento deben actualizarse para mostrar los valores asignados. Los pasos detallados son los siguientes.

  • Crea un objeto de Document.
  • Agregue una sección al documento usando el método Document.addSection().
  • Agregue un párrafo a la sección usando el método Sección.addParagraph().
  • Agregue campos variables al párrafo usando el método Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable).
  • Obtenga la colección de variables utilizando el método Document.getVariables().
  • Asigne un valor a la variable utilizando el método VariableCollection.add().
  • Actualice los campos del documento utilizando el método Document.isUpdateFields().
  • Guarde el documento utilizando el método 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

Cambiar el valor de las variables en documentos de Word

Spire.Doc for Java proporciona el método VariableCollection.set() para cambiar los valores de las variables. Y después de actualizar los campos en el documento, todas las apariciones de las variables mostrarán el valor recién asignado, logrando así un reemplazo de texto rápido y preciso. Los pasos detallados son los siguientes.

  • Crea un objeto de Document.
  • Cargue un documento de Word usando el método Document.loaFromFile().
  • Obtenga la colección de variables utilizando el método Document.getVariables().
  • Asigne un nuevo valor a una variable específica a través de su nombre usando el método VariableCollection.set().
  • Actualice los campos del documento utilizando el método Document.isUpdateFields().
  • Guarde el documento utilizando el método 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

Solicitar 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 문서에서 변수 추가 또는 변경 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>14.5.3</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>14.5.3</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>14.5.3</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>14.5.3</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>14.5.3</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>14.5.3</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-дневную пробную лицензию для себя.

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