page 149

Document properties are some important information contained in Word documents, including title, subject, author, company, keywords, etc. Reading this information can help identify the document, quickly determine the document type or source, and improve the efficiency of document storage and organization. However, if the document properties such as author and company are inappropriate for others to know, you can remove them to protect privacy. This article is going to show how to read or remove document properties 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>13.11.2</version>
    </dependency>
</dependencies>

Read Built-in and Custom Properties from Word Documents

There are two types of properties in Word documents: built-in properties and custom properties. Built-in properties are some predefined properties, while custom properties are properties with custom names, types, and values. The detailed steps for reading the two kinds of document properties are as follows:

  • Create an object of Document.
  • Load a Word document using Document.loadFromFile() method.
  • Get all the built-in properties and custom properties using Document.getBuiltinDocumentProperties() method and Document.getCustomDocumentProperties() method.
  • Get each built-in property using methods under BuiltinDocumentProperties class.
  • Loop through the custom properties to get their name and value using methods under CustomDocumentProperties class.
  • Java
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;

public class GetDocumentProperties {
    public static void main(String[] args) {

        //Create an object of Document
        Document document = new Document();

        //Load a Word document
        document.loadFromFile("C:/Sample.docx");

        //Create an object of StringBuilder
        StringBuilder properties = new StringBuilder();

        //Get all the built-in properties and custom properties
        BuiltinDocumentProperties builtinDocumentProperties = document.getBuiltinDocumentProperties();
        CustomDocumentProperties customDocumentProperties = document.getCustomDocumentProperties();

        //Get each built-in property
        String title = builtinDocumentProperties.getTitle();
        String subject = builtinDocumentProperties.getSubject();
        String author = builtinDocumentProperties.getAuthor();
        String manager = builtinDocumentProperties.getManager();
        String category = builtinDocumentProperties.getCategory();
        String company = builtinDocumentProperties.getCompany();
        String keywords = builtinDocumentProperties.getKeywords();
        String comments = builtinDocumentProperties.getComments();

        //Set string format for displaying
        String builtinProperties = String.format("The built-in properties:\r\nTitle: " + title
                + "\r\nSubject: " + subject + "\r\nAuthor: " + author
                + "\r\nManager: " + manager + "\r\nCategory: " + category
                + "\r\nCompany: " + company + "\r\nKeywords: "+ keywords
                + "\r\nComments:" + comments
        );

        //Add the built-in properties to the StringBuilder object
        properties.append(builtinProperties);

        //Get each custom property
        properties.append("\r\n\r\nThe custom properties:");
        for (int i = 0; i < customDocumentProperties.getCount(); i++) {
            String customProperties = String.format("\r\n" + customDocumentProperties.get(i).getName() + ": " + document.getCustomDocumentProperties().get(i).getValue());

            //Add the custom properties to the StringBuilder object
            properties.append(customProperties);
        }

        //Output the properties of the document
        System.out.println(properties);
    }
}

Java: Read or Remove Properties from Word Documents

Remove Built-in and Custom Properties from Word Documents

Built-in document properties can be removed by setting their values as empty. For custom document properties, we can use the CustomDocumentProperties.get().getName() method to get their name and then use CustomDocumentProperties.remove() method to remove them. The detailed steps are as follows:

  • Create an object of Document.
  • Load a Word document using Document.loadFromFile() method.
  • Get all built-in properties and custom properties using Document.getBuiltinDocumentProperties() method and Document.getCustomDocumentProperties() method.
  • Remove the built-in properties by setting their values as empty using methods under BuiltinDocumentProperties class.
  • Get the count of custom properties using CustomDocumentProperties.getCount() method.
  • Loop through the custom properties, get their names by using CustomDocumentProperties.get().getName() method, and remove each custom property by their name using CustomDocumentProperties.remove() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveDocumentProperties {
    public static void main(String[] args) {

        //Create an object of Document
        Document document = new Document();

        //Load a Word document
        document.loadFromFile("C:/Sample.docx");

        //Get all built-in properties and custom properties
        BuiltinDocumentProperties builtinDocumentProperties = document.getBuiltinDocumentProperties();
        CustomDocumentProperties customDocumentProperties = document.getCustomDocumentProperties();

        //Remove built-in properties by setting their value to empty
        builtinDocumentProperties.setTitle("");
        builtinDocumentProperties.setSubject("");
        builtinDocumentProperties.setAuthor("");
        builtinDocumentProperties.setManager("");
        builtinDocumentProperties.setCompany("");
        builtinDocumentProperties.setCategory("");
        builtinDocumentProperties.setKeywords("");
        builtinDocumentProperties.setComments("");

        //Get the count of custom properties
        int count = customDocumentProperties.getCount();

        //Loop through the custom properties to remove them
        for (int i = count; i > 0; i-- ){

            //Get the name of a custom property
            String name = customDocumentProperties.get(i-1).getName();

            //Remove the custom property by its name
            customDocumentProperties.remove(name);
        }

        //Save the document
        document.saveToFile("RemoveDocumentProperties.docx", FileFormat.Auto);
        document.dispose();
    }
}

Java: Read or Remove Properties from 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.

Java: Create a Fillable Form in Word

2023-03-16 05:54:00 Written by Koohji

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>13.11.2</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.

Math equations in Word documents are essential tools for expressing mathematical concepts and relationships. Whether you are writing an academic paper, a scientific report, or any other document involving mathematical content, incorporating math equations can greatly enhance your ability to convey complex mathematical concepts and improve the visual appeal and professionalism of your document. In this article, we will explain how to insert math equations into Word documents in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Insert Math Equations into a Word Document in C# and VB.NET

Spire.Doc for .NET allows generating math equations from LaTeX code and MathML code using OfficeMath.FromLatexMathCode(string latexMathCode) and OfficeMath.FromMathMLCode(string mathMLCode) methods. The detailed steps are as follows:

  • Create two string arrays from LaTeX code and MathML code.
  • Create a Document instance and add a section to it using Document.AddSection() method.
  • Iterate through each LaTeX code in the string array.
  • Create a math equation from the LaTeX code using OfficeMath.FromLatexMathCode(string latexMathCode) method.
  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.
  • Iterate through each MathML code in the string array.
  • Create a math equation from the MathML code using OfficeMath.FromMathMLCode(string mathMLCode) method.
  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.OMath;

namespace AddMathEquations
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create a string array from LaTeX code
            string[] latexMathCode = {
                "x^{2}+\\sqrt{x^{2}+1}=2",
                "\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta",
                "k_{n+1} = n^2 + k_n^2 - k_{n-1}",
                "\\frac {\\frac {1}{x}+ \\frac {1}{y}}{y-z}",
                "\\int_0^ \\infty \\mathrm {e}^{-x} \\, \\mathrm {d}x",
                "\\forall x \\in X, \\quad \\exists y \\leq \\epsilon",
                "\\alpha, \\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi",
                "A_{m,n} = \\begin{pmatrix} a_{1,1} & a_{1,2} & \\cdots & a_{1,n} \\\\ a_{2,1} & a_{2,2} & \\cdots & a_{2,n} \\\\ \\vdots  & \\vdots  & \\ddots & \\vdots  \\\\ a_{m,1} & a_{m,2} & \\cdots & a_{m,n} \\end{pmatrix}",
            };

            //Create a string array from MathML code
            string[] mathMLCode = {
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><mo>≠</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>x</mi><mo>=</mo><mrow><mfrac><mrow><mo>−</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></mrow></math>",
            };

            //Create a Document instance
            Document doc = new Document();

            //Add a section
            Section section = doc.AddSection();

            //Add a paragraph to the section
            Paragraph textPara = section.AddParagraph();
            textPara.AppendText("Creating Equations from LaTeX Code");
            textPara.ApplyStyle(BuiltinStyle.Heading1);
            textPara.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Iterate through each LaTeX code in the string array
            for (int i = 0; i < latexMathCode.Length; i++)
            {
                //Create a math equation from the LaTeX code
                OfficeMath officeMath = new OfficeMath(doc);
                officeMath.FromLatexMathCode(latexMathCode[i]);
                //Add the math equation to the section
                Paragraph paragraph = section.AddParagraph();                                
                paragraph.Items.Add(officeMath);
                section.AddParagraph();
            }

            section.AddParagraph();

            //Add a paragraph to the section
            textPara = section.AddParagraph();
            textPara.AppendText("Creating Equations from MathML Code");
            textPara.ApplyStyle(BuiltinStyle.Heading1);
            textPara.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Iterate through each MathML code in the string array
            for (int j = 0; j < mathMLCode.Length; j++)
            {
                //Create a math equation from the MathML code
                OfficeMath officeMath = new OfficeMath(doc);
                officeMath.FromMathMLCode(mathMLCode[j]);
                //Add the math equation to the section
                Paragraph paragraph = section.AddParagraph();
                paragraph.Items.Add(officeMath);               
                section.AddParagraph();
            }

            //Save the result document    
            doc.SaveToFile("AddMathEquations.docx", FileFormat.Docx2013);
            doc.Dispose();
        }
    }
}

C#/VB.NET: Insert Math Equations into 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.

page 149

Coupon Code Copied!

Christmas Sale

Celebrate the season with exclusive savings

Save 10% Sitewide

Use Code:

View Campaign Details