When there are overlapping shapes/images in your presentation slide, you can control which shape is under or above which shape by bring a shape forward or to front, or sending a shape backward or to back. The following example shows you how to bring a shape forward using Spire.Presentation with C# and VB.NET.

Code Snippets

[C#]
//load the sample PowerPoint file
Presentation presentation = new Presentation();
presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\input.pptx");

//get the specified shape
IShape shape = presentation.Slides[0].Shapes[0];

//bring the shape forward through SetShapeArrange method
shape.SetShapeArrange(ShapeArrange.BringForward);

//save to file
presentation.SaveToFile("output.pptx", FileFormat.Pptx2013);
[VB.NET]
'load the sample PowerPoint file
Dim presentation As Presentation =  New Presentation() 
presentation.LoadFromFile("C:\Users\Administrator\Desktop\input.pptx")
 
'get the specified shape
Dim shape As IShape =  presentation.Slides(0).Shapes(0) 
 
'bring the shape forward through SetShapeArrange method
shape.SetShapeArrange(ShapeArrange.BringForward)
 
'save to file
presentation.SaveToFile("output.pptx", FileFormat.Pptx2013)

Output

Arrange Shapes in PowerPoint in C#, VB.NET

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

Thursday, 16 March 2023 05:54

Java: Create a Fillable Form in Word

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

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

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

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

Install Spire.Doc for Java

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

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.4.1</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.

Friday, 12 August 2022 08:31

Java: Insert or Remove a Text Box in Word

A text box is an element you can insert and position anywhere in a document. MS Word provides several pre-formatted text boxes, and you can also create custom text boxes with unique appearances to grab the reader's attention. In this article, you will learn how to programmatically insert or remove a text box in a Word document 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>12.4.1</version>
    </dependency>
</dependencies>
    

Insert a Text Box in a Word Document

Spire.Doc for Java provides the Paragraph.appendTextBox(float width, float height) method to insert a text box in a specified paragraph. The detailed steps are as follows.

  • Create a Document instance, and then load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method, and then add a paragraph to the section using Section.addParagraph() method.
  • Add a text box to the paragraph using Paragraph.appendTextBox(float width, float height) method.
  • Get the format of the text box using TextBox.getFormat() method, and then set the text box's wrapping type, position, border color and fill color using the methods under TextBoxFormat Class.
  • Add a paragraph to the text box using TextBox.getBody().addParagraph() method, and then insert an image to the paragraph using Paragraph.appendPicture() method.
  • Insert text to the text box using Paragraph.appendText() method, and then set the text font.
  • Save the document to another file 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.TextBox;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class InsertTextbox {

    public static void main(String[] args) {

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

        //Load a Word document
        doc.loadFromFile("E:\\Files\\Ralph.docx");

        //Append a text box and set its wrapping style
        TextBox tb = doc.getSections().get(0).addParagraph().appendTextBox(120f, 320f);
        tb.getFormat().setTextWrappingStyle(TextWrappingStyle.Square);

        //Set the position of text box
        tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Right_Margin_Area);
        tb.getFormat().setHorizontalPosition(-100f);
        tb.getFormat().setVerticalOrigin(VerticalOrigin.Page);
        tb.getFormat().setVerticalPosition(130f);

        //Set the border color and fill color of the text box
        tb.getFormat().setLineColor(Color.BLUE);
        tb.getFormat().setFillColor(new Color(203,234,253) );

        //Insert an image to text box as a paragraph
        Paragraph para = tb.getBody().addParagraph();
        DocPicture picture = para.appendPicture("C:\\Users\\Administrator\\Desktop\\Ralph.jpg");

        //Set alignment for the paragraph
        para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set the size of the inserted image
        picture.setHeight(90f);
        picture.setWidth(90f);

        //Insert text to text box as the second paragraph
        para = tb.getBody().addParagraph();
        TextRange textRange = para.appendText("Emerson is truly the center of the American transcendental movement, "
                +"setting out most of its ideas and values in a little book, Nature, published in 1836, "
                +"that represented at least ten years of intense study in philosophy, religion, and literature.");

        //Set alignment for the paragraph
        para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set the text font
        textRange.getCharacterFormat().setFontName("Times New Roman");
        textRange.getCharacterFormat().setFontSize(12f);
        textRange.getCharacterFormat().setItalic(true);

        //Save to file
        doc.saveToFile("InsertTextBox.docx", FileFormat.Docx_2013);
    }
}

Java: Insert or Remove a Text Box in Word

Remove a Text Box from a Word Document

Spire.Doc for Java provides the Document.getTextBoxes().removeAt() method to delete a specified text box by index. If you want to delete all text boxes from the Word document, you can use the Document.getTextBoxes().clear() method. The below example shows how to remove the first text box from a Word document.

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Remove the first text box using Document.getTextBoxes().removeAt() method.
  • Save the document to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class DeleteTextbox {

    public static void main(String[] args) {

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

        //Load a Word document
        doc.loadFromFile("E:\\Files\\TextBox.docx");

        //Remove text box by index
        doc.getTextBoxes().removeAt(0);

        //Remove all text boxes
        //doc.getTextBoxes().clear();

        //Save to file
        doc.saveToFile("RemoveTextbox.docx", FileFormat.Docx);
    }
}

Java: Insert or Remove a Text Box 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.

Friday, 24 June 2022 06:51

Java: Insert WordArt in Word

In MS Word, WordArt is used to insert text with special effects such as shadows, outlines, colors, gradients, and 3D effects. It can be helpful when creating stylish headlines or highlighting specific content. In this article, you will learn how to programmatically insert WordArt in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

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

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

Insert WordArt in Word

The ShapeType enumeration provided by Spire.Doc for Java defines a variety of WordArt shape types whose names begin with "Text". In order to create a WordArt in Word, you need to initialize an instance of ShapeObject and specify the WordArt type and text content. The detailed steps are as follows:

  • Create a Document instance.
  • Add a section to the document using Document.addSection() method, and then add a paragraph to the section using Section.addParagraph() method.
  • Append a shape to the paragraph and specify the shape size and type using Paragraph.appendShape(float width, float height, ShapeType shapeType) method.
  • Set the position of the shape using ShapeObject.setVerticalPosition() and ShapeObject.setHorizontalPosition() methods.
  • Set the text of WordArt using ShapeObject.getWordArt().setText() method.
  • Set the fill color and stroke color of WordArt using ShapeObject.setFillColor() and ShapeObject.setStrokeColor() methods.
  • Save the document to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;


public class WordArt{
    public static void main(String[] args) throws Exception {
        //Create a Document instance
        Document doc = new Document();

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

        //Add a paragraph.
        Paragraph paragraph = section.addParagraph();

        //Add a shape to the paragraph and specify the shape size and type
        ShapeObject shape = paragraph.appendShape(400, 150, ShapeType.Text_Deflate_Bottom);

        //Set the position of the shape
        shape.setVerticalPosition(60);
        shape.setHorizontalPosition(60);

        //set the text of WordArt
        shape.getWordArt().setText("Create WordArt in Word");

        // Set the fill color and stroke color of WordArt
        shape.setFillColor(Color.CYAN);
        shape.setStrokeColor(Color.BLUE);

        //save the document to file.
        doc.saveToFile("WordArt.docx", FileFormat.Docx_2013);
    }
}

Java: Insert WordArt 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.

Thursday, 01 December 2022 07:14

Java: Add Document Properties to Word Documents

The properties of a document are a set of information about the document and its content, such as title, subject, author's name, manager, company, category, keywords (also known as tags), and comments. This information does not appear in the content of the document, but it can help you better search, sort, and filter files. In this article, you will learn how to add document properties to Word documents in Java 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>12.4.1</version>
    </dependency>
</dependencies>
    

Add Built-in Document Properties to a Word Document in Java

A built-in document property (also known as a standard document property) consists of a name and a value. You cannot set or change the name of a built-in document property as it’s predefined by Microsoft Word, but you can set or change its value. The following steps demonstrate how to set values for built-in document properties in a Word document in Java using Spire.Doc for Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Access the built-in document properties of the document using Document.getBuiltinDocumentProperties() method.
  • Set the values of specific document properties such as title, subject and author using setTitle(), setSubject() and setAuthor() methods provided by BuiltinDocumentProperties class.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class AddBuiltinDocumentProperties {
    public static void main(String []args) throws Exception {
        //Create a Document instance
        Document document = new Document();
        //Load a Word document
        document.loadFromFile("Sample.docx");

        //Access the built-in document properties of the document
        BuiltinDocumentProperties standardProperties = document.getBuiltinDocumentProperties();
        //Set the values of specific built-in document properties 
        standardProperties.setTitle("Add Document Properties");
        standardProperties.setSubject("Java Example");
        standardProperties.setAuthor("James");
        standardProperties.setCompany("Eiceblue");
        standardProperties.setManager("Michael");
        standardProperties.setCategory("Document Manipulation");
        standardProperties.setKeywords("Java, Word, Document Properties");
        standardProperties.setComments("This article shows how to add document properties");

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

Java: Add Document Properties to Word Documents

Add Custom Document Properties to a Word Document in Java

A custom document property can be defined by a document author or user. Each custom document property should contain a name, a value and a data type. The data type can be one of these four types: Text, Date, Number and Yes or No. The following steps demonstrate how to add custom document properties with different data types to a Word document in Java using Spire.Doc for Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Access the custom document properties of the document using Document.getCustomDocumentProperties() method.
  • Add custom document properties with different data types to the document using CustomDocumentProperties.add(String, Object) method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.util.Date;

public class AddCustomDocumentProperties {
    public static void main(String []args) throws Exception {
        //Create a Document instance
        Document document = new Document();
        //Load a Word document
        document.loadFromFile("Sample.docx");

        //Access the custom document properties of the document
        CustomDocumentProperties customProperties = document.getCustomDocumentProperties();
        //Add custom document properties with different data types to the document
        customProperties.add("Document ID", 1);
        customProperties.add("Authorized", true);
        customProperties.add("Authorized By", "John Smith");
        customProperties.add("Authorized Date", new Date());

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

Java: Add Document Properties to 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.

Tuesday, 05 July 2022 07:35

C#/VB.NET: Digitally Sign Word Documents

A signature confirms that the digital document originated from the signer and has not been tampered with during transit. The use of digital signatures eliminates the need for sending paper documents, and reduces the number of the documents that need to be printed, mailed, and stored, saving you time and money. In this article, you will learn how to digitally sign a Word document 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

Add a Digital Signature to Word in C#, VB.NET

The steps are as follows.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Specify the path and the password of a .pfx certificate.
  • Digitally sign the document while saving the document using Document.SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword) method. Here are some other methods that you can use to digitally sign a Word document.
    • public void SaveToFile(string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
    • public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] certificateData, string securePassword);
    • public void SaveToStream(Stream stream, FileFormat fileFormat, string certificatePath, string securePassword);
    • public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
    • public static byte[] Document.Sign(Stream sourceStream, string certificatePath, string securePassword);
  • C#
  • VB.NET
using Spire.Doc;

namespace DigitallySignWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Load a Word file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

            //Specify the certificate path
            string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";

            //Specify the password of the certificate
            string password = "e-iceblue";

            //Digitally sign the document while saving it to a .docx file
            doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
        }
    }
}

C#/VB.NET: Digitally Sign 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.

Besides the Combo Box, Text, Date Picker and Drop-Down List content controls, Checkbox and picture content control also are the mostly used content control in word document. Spire.Doc supports to add many kinds of content controls to the word document. This article will show you how to add checkbox and picture content control to word document by Spire.Doc for .NET.

Code snippets of how to add checkbox and picture content control:

using System;
using System.Drawing;
namespace AddCheckbox
{

    class Program
    {

        static void Main(string[] args)
        {
            //Create a new word document
            Document document = new Document();

            //Add a section to the document
            Section section = document.AddSection();

            //Add a document to the section
            Paragraph paragraph = section.AddParagraph();

            //Add checkbox content control
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(document);
            paragraph = section.AddParagraph();
            sdt = new StructureDocumentTagInline(document);
            sdt.CharacterFormat.FontSize = 20;
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.CheckBox;
            SdtCheckBox scb = new SdtCheckBox();
            sdt.SDTProperties.ControlProperties = scb;
            TextRange tr = new TextRange(document);
            tr.CharacterFormat.FontName = "MS Gothic";
            tr.CharacterFormat.FontSize = 20;
            sdt.ChildObjects.Add(tr);
            scb.Checked = true;

            sdt.SDTProperties.Alias = "CheckoBox";
            sdt.SDTProperties.Tag = "Checkbox";

            //Add picture content control
            paragraph = section.AddParagraph();
            sdt = new StructureDocumentTagInline(document);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.ControlProperties = new SdtPicture();

            sdt.SDTProperties.Alias = "Picture";
            sdt.SDTProperties.Tag = "Picture";

            DocPicture pic = new DocPicture(document) { Width = 10, Height = 10 };
            pic.LoadImage(Image.FromFile("Logo.jpg"));
            sdt.SDTContent.ChildObjects.Add(pic);

            document.SaveToFile("Sample.docx", FileFormat.Docx2013);

        }
    }
}

Effective screenshot after adding checkbox and picture content control to word document:

Add checkbox and picture content control to word document in C#

Headers are text or pictures on the top of pages in Word documents while footers are at the bottom. People usually use headers and footers to display some important information about documents, such as copyright, author information, and page numbers or just to make the document more good-looking and professional. They can be inserted into a Word document on every page, only on the first page, or differently on odd pages and even pages. This article will show how to insert headers and footers into Word documents programmatically using Spire.Doc for Java.

Install Spire.Doc for Java

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

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

Insert Headers and Footers into a Word Document

To insert a header or a footer into a Word document using Spire.Doc for Java, you need to use Section.getHeadersFooters().getHeader() and Section.getHeadersFooters().getFooter() methods to get them and then add paragraphs to them to insert pictures, text, or page number fields.

The detailed steps for inserting headers and footers are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.loadFromFIle() method.
  • Get the first section using Document.getSections().get() method.
  • Call the custom method insertHeaderAndFooter() to insert a header and a footer into the section.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

public class insertHeaderAndFooter {

    public static void main(String[] args) {

        //Create a Document class instance
        Document document = new Document();

        //Load a Word document
        document.loadFromFile("We Are Interwoven Beings.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Call the custom method insertHeaderAndFooter() to insert headers and footers to the section
        insertHeaderAndFooter(section);

        //Save the document
        document.saveToFile("HeaderAndFooter.docx", FileFormat.Docx);
    }

    private static void insertHeaderAndFooter(Section section) {



        //Get header and footer from a section
        HeaderFooter header = section.getHeadersFooters().getHeader();
        HeaderFooter footer = section.getHeadersFooters().getFooter();

        //Add a paragraph to the header
        Paragraph headerParagraph = header.addParagraph();

        //Add text to the header paragraph
        TextRange text = headerParagraph.appendText("Philosophy\rWe Are Interwoven Beings");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(12);
        text.getCharacterFormat().setItalic(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set the bottom border style of the header paragraph
        headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);
        headerParagraph.getFormat().getBorders().getBottom().setLineWidth(1f);

        //Add a paragraph to the footer
        Paragraph footerParagraph = footer.addParagraph();

        //Add Field_Page and Field_Num_Pages fields to the footer paragraph
        footerParagraph.appendField("Page Number", FieldType.Field_Page);
        footerParagraph.appendText(" of ");
        footerParagraph.appendField("Number of Pages", FieldType.Field_Num_Pages);
        footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set the top border style of the footer paragraph
        footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
        footerParagraph.getFormat().getBorders().getTop().setLineWidth(1f);
    }
}

Java: Insert Headers and Footers into Word Documents

Insert a Header and a Footer Only into the First Page of a Word Document

Sometimes we only need to insert a header and a footer into the first page, which can be realized by Spire.Doc for Java as well. We can use Section.getPageSetup().setDifferentFirstPageHeaderFooter() method to make the headers and footers of the first page different from other pages.

The detailed steps for inserting header and footer only into the first page are as follows:

  • Create a Document class instance.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Make the headers and footers of the first page different from other pages using Section.getPageSetup().setDifferentFirstPageHeaderFooter() method.
  • Call the custom method insertHeaderAndFooterFirst() to insert a header and a footer into the first page.
  • 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.awt.*;

public class insertHeaderAndFooter {

    public static void main(String[] args) {

        //Create a Document class instance
        Document document = new Document();

        //Load a Word document
        document.loadFromFile("We Are Interwoven Beings.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Make the headers and footers of the first page different from other pages
        section.getPageSetup().setDifferentFirstPageHeaderFooter(true);

        //Call the custom method insertHeaderAndFooterFirst() to insert a header and a footer into the first page
        insertHeaderAndFooterFirst(section);

        //Save the document
        document.saveToFile("FirstPageHeaderAndFooter.docx", FileFormat.Docx);
    }

    private static void insertHeaderAndFooterFirst(Section section) {

        //Get header and footer of the first page
        HeaderFooter header = section.getHeadersFooters().getFirstPageHeader();
        HeaderFooter footer = section.getHeadersFooters().getFirstPageFooter();

        //Add a paragraph to the header
        Paragraph headerParagraph = header.addParagraph();

        //Add text to the header paragraph
        TextRange text = headerParagraph.appendText("Philosophy");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(14);
        text.getCharacterFormat().setTextColor(Color.blue);
        text.getCharacterFormat().setItalic(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

        //Insert a picture into the header paragraph and set its position
        DocPicture headerPicture = headerParagraph.appendPicture("Header.png");
        headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left);
        headerPicture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
        headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Center);

        //Set text wrapping style to Behind
        headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind);

        //Set the bottom border style of the header paragraph
        headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);
        headerParagraph.getFormat().getBorders().getBottom().setLineWidth(1f);

        //Add a paragraph to the footer
        Paragraph footerParagraph = footer.addParagraph();

        //Add text to the footer paragraph
        TextRange text1 = footerParagraph.appendText("We Are Interwoven Beings");
        text1.getCharacterFormat().setFontName("Arial");
        text1.getCharacterFormat().setFontSize(14);
        text1.getCharacterFormat().setTextColor(Color.BLUE);
        text1.getCharacterFormat().setItalic(true);
        footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set the top border style of the footer paragraph
        footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
        footerParagraph.getFormat().getBorders().getTop().setLineWidth(1f);
    }
}

Java: Insert Headers and Footers into Word Documents

Insert Different Headers and Footers into Odd Pages and Even Pages

We may also encounter situations where we need to insert different headers and footers into odd pages and even pages. Spire.Doc for Java provides a method Section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter(), which can make headers and footers different on odd pages and even pages, to meet such needs.

The detailed steps for inserting different headers and footers into odd pages and even pages are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Make the headers and footers of odd pages and even pages different using Section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter() method.
  • Call the custom method insertHeaderAndFooterOddEven() to insert different headers and footers into odd pages and even pages.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class insertHeaderAndFooter {

    public static void main(String[] args) {

        //Create a Document class instance
        Document document = new Document();

        //Load a Word document
        document.loadFromFile("We Are Interwoven Beings.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Make the headers and footers of odd pages and even pages different
        section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter(true);

        //Call the custom method insertHeaderAndFooterOddEven() to insert different headers and footers into odd pages and even pages
        insertHeaderAndFooterOddEven(section);

        //Save the document
        document.saveToFile("OddEvenHeaderAndFooter.docx", FileFormat.Docx);
    }

    private static void insertHeaderAndFooterOddEven(Section section) {

        //Insert odd header
        Paragraph P1 = section.getHeadersFooters().getOddHeader().addParagraph();
        TextRange OH = P1.appendText("Odd Header");
        P1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        OH.getCharacterFormat().setFontName("Arial");
        OH.getCharacterFormat().setFontSize(16);
        OH.getCharacterFormat().setTextColor(Color.RED);

        //Insert even header
        Paragraph P2 = section.getHeadersFooters().getEvenHeader().addParagraph();
        TextRange EH = P2.appendText("Even Header");
        P2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        EH.getCharacterFormat().setFontName("Arial");
        EH.getCharacterFormat().setFontSize(16);
        EH.getCharacterFormat().setTextColor(Color.RED);

        //Insert odd footer
        Paragraph P3 = section.getHeadersFooters().getOddFooter().addParagraph();
        TextRange OF = P3.appendText("Odd Footer");
        P3.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        OF.getCharacterFormat().setFontName("Arial");
        OF.getCharacterFormat().setFontSize(16);
        OF.getCharacterFormat().setTextColor(Color.RED);

        //Insert even footer
        Paragraph P4 = section.getHeadersFooters().getEvenFooter().addParagraph();
        TextRange EF = P4.appendText("Even Footer");
        EF.getCharacterFormat().setFontName("Arial");
        EF.getCharacterFormat().setFontSize(16);
        P4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        EF.getCharacterFormat().setTextColor(Color.RED);
    }
}

Java: Insert Headers and Footers 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.