Java: Modify Content Controls in Word documents

2024-05-09 06:08:59 Written by  support iceblue
Rate this item
(0 votes)

In a Word document, content controls are special elements that can be used to add interactivity and dynamic content, making the document more interactive and functional. Through content controls, users can easily insert, delete, or modify content in specific sections without altering the overall structure of the document, making it easier to create various types of documents and improve efficiency. This article will introduce how to use Spire.Doc for Java to modify content controls in Word documents within a Java project.

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

Modify Content Controls in the Body using Java

In Spire.Doc, to modify content controls in the body, you need to work with objects of the StructureDocumentTag type. By iterating through the collection of child objects in Section.getBody(), you can find objects of type StructureDocumentTag and make the necessary changes. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Get the body of a section in the document using Section.getBody().
  • Iterate through the collection of child objects in the body using Body.getChildObjects() to find objects of type StructureDocumentTag.
  • Access the collection of child objects in StructureDocumentTag.getChildObjects() and perform the required modifications based on the type of the child objects.
  • Save the document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import java.util.*;

public class ModifyContentControlInBody {
    public static void main(String[] args) {
        // Create a new document object
        Document doc = new Document();

        // Load document content from file
        doc.loadFromFile("Sample1.docx");

        // Get the body of the document
        Body body = doc.getSections().get(0).getBody();

        // Create lists for paragraphs and tables
        List<Paragraph> paragraphs = new ArrayList<>();
        List<Table> tables = new ArrayList<>();
        for (int i = 0; i < body.getChildObjects().getCount(); i++) {

            // Get the document object
            DocumentObject documentObject = body.getChildObjects().get(i);

            // If it is a StructureDocumentTag object
            if (documentObject instanceof StructureDocumentTag) {
                StructureDocumentTag structureDocumentTag = (StructureDocumentTag) documentObject;

                // If the tag is "c1" or the alias is "c1"
                if (structureDocumentTag.getSDTProperties().getTag().equals("c1") || structureDocumentTag.getSDTProperties().getAlias().equals("c1")) {
                    for (int j = 0; j < structureDocumentTag.getChildObjects().getCount(); j++) {
                        // If it is a paragraph object
                        if (structureDocumentTag.getChildObjects().get(j) instanceof Paragraph) {
                            Paragraph paragraph = (Paragraph) structureDocumentTag.getChildObjects().get(j);
                            paragraphs.add(paragraph);
                        }

                        // If it is a table object
                        if (structureDocumentTag.getChildObjects().get(j) instanceof Table) {
                            Table table = (Table) structureDocumentTag.getChildObjects().get(j);
                            tables.add(table);
                        }
                    }
                }
            }
        }

        // Modify the text content of the first paragraph
        paragraphs.get(0).setText("Chengdu E-iceblue Co., Ltd. is committed to providing JAVA component development products for developers.");

        // Reset the cells of the first table to 5 rows and 4 columns
        tables.get(0).resetCells(5, 4);

        // Save the modified document to a file
        doc.saveToFile("Modify Content Controls in Word Document Body.docx", FileFormat.Docx_2016);

        // Close the document and release document resources
        doc.close();
        doc.dispose();
    }
}

Java: Modify Content Controls in Word documents

Modify Content Controls within Paragraphs using Java

In Spire.Doc, to modify content controls within a paragraph, you need to use objects of type StructureDocumentTagInline. The specific steps involve iterating through the collection of child objects in a paragraph, finding objects of type StructureDocumentTagInline, and then making the necessary modifications. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Get the body of a section using Section.getBody().
  • Retrieve the first paragraph of the body using Body.getParagraphs().get(0).
  • Iterate through the collection of child objects in the paragraph using Paragraph.getChildObjects() to find objects of type StructureDocumentTagInline.
  • Access the collection of child objects in StructureDocumentTagInline using StructureDocumentTagInline.getChildObjects() and perform the necessary modifications based on the type of child objects.
  • Save the document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class ModifyContentControlInParagraph {
    public static void main(String[] args) {
        // Create a new Document object
        Document doc = new Document();

        // Load document content from a file
        doc.loadFromFile("Sample2.docx");

        // Get the body of the document
        Body body = doc.getSections().get(0).getBody();

        // Get the first paragraph of the body
        Paragraph paragraph = body.getParagraphs().get(0);

        // Iterate through the child objects in the paragraph
        for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {

            // Check if the child object is of type StructureDocumentTagInline
            if (paragraph.getChildObjects().get(i) instanceof StructureDocumentTagInline) {

                // Convert the child object to StructureDocumentTagInline type
                StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline) paragraph.getChildObjects().get(i);

                // Check if the Tag or Alias property of the document tag is "text1"
                if (structureDocumentTagInline.getSDTProperties().getTag().equals("text1") || structureDocumentTagInline.getSDTProperties().getAlias().equals("text1")) {

                    // Iterate through the child objects in the StructureDocumentTagInline object
                    for (int j = 0; j < structureDocumentTagInline.getChildObjects().getCount(); j++) {

                        // Check if the child object is a TextRange object
                        if (structureDocumentTagInline.getChildObjects().get(j) instanceof TextRange) {

                            // Convert the child object to TextRange type
                            TextRange range = (TextRange) structureDocumentTagInline.getChildObjects().get(j);

                            // Set the text content to the specified content
                            range.setText("Word97-2003, Word2007, Word2010, Word2013, Word2016, and Word2019");
                        }
                    }
                }

                // Check if the Tag or Alias property of the document tag is "logo1"
                if (structureDocumentTagInline.getSDTProperties().getTag().equals("logo1") || structureDocumentTagInline.getSDTProperties().getAlias().equals("logo1")) {

                    // Iterate through the child objects in the StructureDocumentTagInline object
                    for (int j = 0; j < structureDocumentTagInline.getChildObjects().getCount(); j++) {

                        // Check if the child object is an image
                        if (structureDocumentTagInline.getChildObjects().get(j) instanceof DocPicture) {

                            // Convert the child object to DocPicture type
                            DocPicture docPicture = (DocPicture) structureDocumentTagInline.getChildObjects().get(j);

                            // Load the specified image
                            docPicture.loadImage("Doc-Java.png");

                            // Set the width and height of the image
                            docPicture.setWidth(100);
                            docPicture.setHeight(100);
                        }
                    }
                }
            }
        }

        // Save the modified document to a new file
        doc.saveToFile("Modified Content Controls in Paragraphs of a Word Document.docx", FileFormat.Docx_2016);

        // Close the document and release document resources
        doc.close();
        doc.dispose();
    }
}

Java: Modify Content Controls in Word documents

Modify Content Controls Wrapping Table Rows using Java

In Spire.Doc, to modify content controls in table rows, you need to iterate through the collection of table's child objects, find objects of type StructureDocumentTagRow, and then make the necessary changes. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Get the body of a section in the document using Section.getBody().
  • Get the first table in the body using Body.getTables().get(0).
  • Iterate through the table's child objects collection using Table.getChildObjects() to find objects of type StructureDocumentTagRow.
  • Access the cell collection of the table row content controls using StructureDocumentTagRow.getCells(), and then perform the required modifications on the cell contents.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;

public class ModifyTextContentControlInTableRow {
    public static void main(String[] args) {
        // Create a new document object
        Document doc = new Document();

        // Load a document from a file
        doc.loadFromFile("Sample3.docx");

        // Get the body of the document
        Body body = doc.getSections().get(0).getBody();

        // Get the first table
        Table table = body.getTables().get(0);

        // Iterate through the child objects in the table
        for (int i = 0; i < table.getChildObjects().getCount(); i++) {

            // Check if the child object is of type StructureDocumentTagRow
            if (table.getChildObjects().get(i) instanceof StructureDocumentTagRow) {

                // Convert the child object to a StructureDocumentTagRow object
                StructureDocumentTagRow structureDocumentTagRow = (StructureDocumentTagRow) table.getChildObjects().get(i);

                // Check if the Tag or Alias property of the StructureDocumentTagRow is "row1"
                if (structureDocumentTagRow.getSDTProperties().getTag().equals("row1") || structureDocumentTagRow.getSDTProperties().getAlias().equals("row1")) {

                    // Clear the paragraphs in the cell
                    structureDocumentTagRow.getCells().get(0).getParagraphs().clear();

                    // Add a paragraph in the cell and set the text
                    TextRange textRange = structureDocumentTagRow.getCells().get(0).addParagraph().appendText("Art");
                    textRange.getCharacterFormat().setTextColor(Color.BLUE);
                }
            }
        }

        // Save the modified document to a file
        doc.saveToFile("ModifiedTableRowContentControl.docx", FileFormat.Docx_2016);

        // Close the document and release the document resources
        doc.close();
        doc.dispose();
    }
}

Java: Modify Content Controls in Word documents

Modify Content Controls Wrapping Table Cells using Java

In Spire.Doc, to manipulate content control objects in table cells, you need to use a specific type of object called StructureDocumentTagCell. This can be done by examining the collection of child objects in TableRow.getChildObjects(), finding objects of type StructureDocumentTagCell, and then performing the necessary operations. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Get the body of a section in the document using Section.getBody().
  • Get the first table in the body using Body.getTables().get(0).
  • Iterate through the collection of table rows using Table.getRows() and access each TableRow object.
  • Iterate through the collection of child objects in the table row using TableRow.getChildObjects() to find objects of type StructureDocumentTagCell.
  • Access the collection of paragraphs in StructureDocumentTagCell.getParagraphs() for the content control in the table cell and perform the necessary modifications on the content.
  • Save the document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;

public class ModifyTextContentControlInTableCell {
    public static void main(String[] args) {
        // Create a new document object
        Document doc = new Document();

        // Load the document from a file
        doc.loadFromFile("Sample4.docx");

        // Get the body of the document
        Body body = doc.getSections().get(0).getBody();

        // Get the first table in the document
        Table table = body.getTables().get(0);

        // Iterate through the rows of the table
        for (int i = 0; i < table.getRows().getCount(); i++) {

            // Iterate through the child objects in each row
            for (int j = 0; j < table.getRows().get(i).getChildObjects().getCount(); j++) {

                // Check if the child object is a StructureDocumentTagCell
                if (table.getRows().get(i).getChildObjects().get(j) instanceof StructureDocumentTagCell) {

                    // Convert the child object to StructureDocumentTagCell type
                    StructureDocumentTagCell structureDocumentTagCell = (StructureDocumentTagCell) table.getRows().get(i).getChildObjects().get(j);

                    // Check if the Tag or Alias property of structureDocumentTagCell is "cell1"
                    if (structureDocumentTagCell.getSDTProperties().getTag().equals("cell1") || structureDocumentTagCell.getSDTProperties().getAlias().equals("cell1")) {

                        // Clear the paragraphs in the cell
                        structureDocumentTagCell.getParagraphs().clear();

                        // Add a new paragraph and append text to it
                        TextRange textRange = structureDocumentTagCell.addParagraph().appendText("92");
                        textRange.getCharacterFormat().setTextColor(Color.BLUE);
                    }
                }
            }
        }

        // Save the modified document to a new file
        doc.saveToFile("ModifiedTableCellContentControl.docx", FileFormat.Docx_2016);

        // Close the document and release the document resources
        doc.close();
        doc.dispose();
    }
}

Java: Modify Content Controls in Word documents

Modify Content Controls within Table Cells using Java

This example demonstrates how to modify content controls in paragraphs within table cells. Firstly, you need to access the collection of paragraphs in a cell using TableCell.getParagraphs(), then iterate through the child objects collection of each paragraph using Paragraph.getChildObjects(), and search for objects of type StructureDocumentTagInline within it for modification.

  • Create a Document object.
  • Load a document using Document.loadFromFile() method.
  • Get the body of a section in the document using Section.getBody().
  • Get the first table in the body using Body.getTables().get(0).
  • Iterate through the collection of table rows using Table.getRows(), accessing each TableRow object.
  • Iterate through the collection of cells in a row using TableRow.getCells(), accessing each TableCell object.
  • Iterate through the collection of paragraphs in a cell using TableCell.getParagraphs(), accessing each Paragraph object.
  • Iterate through the collection of child objects in a paragraph using Paragraph.getChildObjects(), looking for objects of type StructureDocumentTagInline.
  • Access the collection of child objects in StructureDocumentTagInline using StructureDocumentTagInline.getChildObjects(), and perform the necessary modification based on the type of child object.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;

public class ModifyTextContentControlInParagraphOfTableCell {
    public static void main(String[] args) {
        // Create a new Document object
        Document doc = new Document();

        // Load document content from a file
        doc.loadFromFile("Sample5.docx");

        // Get the body of the document
        Body body = doc.getSections().get(0).getBody();

        // Get the first table
        Table table = body.getTables().get(0);

        // Iterate through the rows of the table
        for (int r = 0; r < table.getRows().getCount(); r++) {

            // Iterate through the cells in the table row
            for (int c = 0; c < table.getRows().get(r).getCells().getCount(); c++) {

                // Iterate through the paragraphs in the cell
                for (int p = 0; p < table.getRows().get(r).getCells().get(c).getParagraphs().getCount(); p++) {

                    // Get the paragraph object
                    Paragraph paragraph = table.getRows().get(r).getCells().get(c).getParagraphs().get(p);

                    // Iterate through the child objects in the paragraph
                    for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {

                        // Check if the child object is of type StructureDocumentTagInline
                        if (paragraph.getChildObjects().get(i) instanceof StructureDocumentTagInline) {

                            // Convert it to a StructureDocumentTagInline object
                            StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline) paragraph.getChildObjects().get(i);

                            // Check if the Tag or Alias property of StructureDocumentTagInline is "test1"
                            if (structureDocumentTagInline.getSDTProperties().getTag().equals("test1") || structureDocumentTagInline.getSDTProperties().getAlias().equals("test1")) {

                                // Iterate through the child objects of StructureDocumentTagInline
                                for (int j = 0; j < structureDocumentTagInline.getChildObjects().getCount(); j++) {

                                    // Check if the child object is of type TextRange
                                    if (structureDocumentTagInline.getChildObjects().get(j) instanceof TextRange) {

                                        // Convert it to a TextRange object
                                        TextRange textRange = (TextRange) structureDocumentTagInline.getChildObjects().get(j);

                                        // Set the text content
                                        textRange.setText("89");

                                        // Set the text color
                                        textRange.getCharacterFormat().setTextColor(Color.BLUE);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Save the modified document to a new file
        doc.saveToFile("ModifiedContentControlInParagraphsOfTableCell.docx", FileFormat.Docx_2016);

        // Close the document and release document resources
        doc.close();
        doc.dispose();
    }
}

Java: Modify Content Controls 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.