News Category

Adding gutters on Word document pages can assist users in better page layout and design, especially when preparing documents for printing or creating books that require gutter. Gutter can indicate the gutter position on the page, helping users to design with appropriate blank areas to avoid text or images being cut off. By setting gutter, users can have better control over the appearance and layout of the document, ensuring that the final output meets the expected gutter requirements, enhancing the professionalism and readability of the document. This article shows how to add gutters on Word document pages by programming 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.6</version>
    </dependency>
</dependencies>
    

Add a Gutter at the Top of a Word Document Page in Java

In a Word document, you can set section.getPageSetup().isTopGutter(true) to place the gutter at the top of the page. By default, the gutter area is displayed as blank without any content. This example also includes steps on how to add content, such as the dash symbol, to the gutter area to customize content around the gutter. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Iterate through all sections of the document using a for loop and Document.getSections().
  • Set Section.getPageSetup().isTopGutter(true) to display the gutter at the top of the page.
  • Use Section.getPageSetup().setGutter() to set the width of the gutter.
  • Call the custom addTopGutterContent() method to add content to the gutter area.
  • Save the document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.formatting.CharacterFormat;
import java.awt.*;

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

        // Load the document
        document.loadFromFile("Sample1.docx");

        // Iterate through all sections of the document
        for (int i = 0; i < document.getSections().getCount(); i++) {
            // Get the current section
            Section section = document.getSections().get(i);

            // Set whether to add a gutter at the top of the page to true
            section.getPageSetup().isTopGutter(true);

            // Set the width of the gutter to 100f
            section.getPageSetup().setGutter(100f);

            // Call the method to add content to the top gutter
            addTopGutterContent(section);
        }

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

        // Release document resources
        document.dispose();
    }

    // Method to add content to the top gutter
    static void addTopGutterContent(Section section) {
        // Get the header of the section
        HeaderFooter header = section.getHeadersFooters().getHeader();

        // Set the width of the text box to the width of the page
        float width = (float) section.getPageSetup().getPageSize().getWidth();

        // Set the height of the text box to 40
        float height = 40;

        // Add a text box to the header
        TextBox textBox = header.addParagraph().appendTextBox(width, height);

        // Set the text box without borders
        textBox.getFormat().setNoLine(true);

        // Set the vertical origin of the text box to the top margin area
        textBox.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);

        // Set the vertical position of the text box
        textBox.setVerticalPosition(140);

        // Set the horizontal alignment of the text box to left
        textBox.setHorizontalAlignment(ShapeHorizontalAlignment.Left);

        // Set the horizontal origin of the text box to the left margin area
        textBox.setHorizontalOrigin(HorizontalOrigin.Left_Margin_Area);

        // Set the text anchor to the bottom
        textBox.getFormat().setTextAnchor(ShapeVerticalAlignment.Bottom);

        // Set the text wrapping style to in front of text
        textBox.getFormat().setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text);

        // Set the text wrapping type to both sides
        textBox.getFormat().setTextWrappingType(TextWrappingType.Both);

        // Create a paragraph object
        Paragraph paragraph = new Paragraph(section.getDocument());

        // Set the paragraph alignment to center
        paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        // Create a font object
        Font font = new Font("SimSun", Font.PLAIN, 8);

        Graphics graphics = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB).getGraphics();
        graphics.setFont(font);
        FontMetrics fontMetrics = graphics.getFontMetrics();
        String text1 = " - ";
        int textWidth1 = fontMetrics.stringWidth(text1);
        int count = (int) (textBox.getWidth() / textWidth1);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i < count; i++) {
            stringBuilder.append(text1);
        }
        // Create a character format object
        CharacterFormat characterFormat = new CharacterFormat(section.getDocument());
        characterFormat.setFontName(font.getFontName());
        characterFormat.setFontSize(font.getSize());
        TextRange textRange = paragraph.appendText(stringBuilder.toString());
        textRange.applyCharacterFormat(characterFormat);

        // Add the paragraph to the text box
        textBox.getChildObjects().add(paragraph);
    }
}

Java: Add Gutters on Word document pages

Add a Gutter at the Left of a Word Document Page in Java

To set the gutter on the left side of the page, the key is to set Section.getPageSetup().isTopGutter(false). Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Iterate through all sections of the document using a for loop and Document.getSections().
  • Set Section.getPageSetup().isTopGutter(false) to display the gutter on the left side of the page.
  • Use Section.getPageSetup().setGutter() to set the width of the gutter.
  • Call the custom addLeftGutterContent() method to add content to the gutter area.
  • Save the document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.formatting.CharacterFormat;
import java.awt.*;

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

        // Load the document
        document.loadFromFile("Sample1.docx");

        // Iterate through all sections of the document
        for (int i = 0; i < document.getSections().getCount(); i++) {
            // Get the current section
            Section section = document.getSections().get(i);

            // Set whether to add a gutter at the top of the page to false, it will be added to the left side of the page
            section.getPageSetup().isTopGutter(false);

            // Set the width of the gutter to 100f
            section.getPageSetup().setGutter(100f);

            // Call the method to add content to the left gutter
            AddLeftGutterContent (section);
        }

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

        // Release document resources
        document.dispose();
    }

    // Method to add content to the left gutter
    static void AddLeftGutterContent(Section section) {
        // Get the header of the section
        HeaderFooter header = section.getHeadersFooters().getHeader();

        // Set the width of the text box to 40
        float width = 40;

        // Get the page height
        float height = (float) section.getPageSetup().getPageSize().getHeight();

        // Add a text box to the header
        TextBox textBox = header.addParagraph().appendTextBox(width, height);

        // Set the text box without borders
        textBox.getFormat().setNoLine(true);

        // Set the text direction in the text box from right to left
        textBox.getFormat().setLayoutFlowAlt(TextDirection.Right_To_Left);

        // Set the horizontal starting position of the text box
        textBox.setHorizontalOrigin(HorizontalOrigin.Left_Margin_Area);

        // Set the horizontal position of the text box
        textBox.setHorizontalPosition(140);

        // Set the vertical alignment of the text box to the top
        textBox.setVerticalAlignment(ShapeVerticalAlignment.Top);

        // Set the vertical origin of the text box to the top margin area
        textBox.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);

        // Set the text anchor to the top
        textBox.getFormat().setTextAnchor(ShapeVerticalAlignment.Top);

        // Set the text wrapping style to in front of text
        textBox.getFormat().setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text);

        // Set the text wrapping type to both sides
        textBox.getFormat().setTextWrappingType(TextWrappingType.Both);

        // Create a paragraph object
        Paragraph paragraph = new Paragraph(section.getDocument());

        // Set the paragraph alignment to center
        paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        // Create a font object, SimSun, size 8
        Font font = new Font("SimSun", Font.PLAIN, 8);

        Graphics graphics = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB).getGraphics();
        graphics.setFont(font);
        FontMetrics fontMetrics = graphics.getFontMetrics();
        String text1 = " - ";
        int textWidth1 = fontMetrics.stringWidth(text1);
        int count = (int) (textBox.getHeight() / textWidth1);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i < count ; i++) {
            stringBuilder.append(text1);
        }

        // Create a character format object
        CharacterFormat characterFormat = new CharacterFormat(section.getDocument());
        characterFormat.setFontName(font.getFontName());
        characterFormat.setFontSize(font.getSize());
        TextRange textRange = paragraph.appendText(stringBuilder.toString());
        textRange.applyCharacterFormat(characterFormat);

        // Add the paragraph to the text box
        textBox.getChildObjects().add(paragraph);
    }
}

Java: Add Gutters on Word document pages

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.

Extracting content from Word documents plays a crucial role in both work and study. Extracting one page of content helps in quickly browsing and summarizing key points, while extracting content from one section aids in in-depth study of specific topics or sections. Extracting the entire document allows you to have a comprehensive understanding of the document content, facilitating deep analysis and comprehensive comprehension. This article will introduce how to use Spire.Doc for Java to read a page, a section, and the entire content of a Word document in 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.4.6</version>
    </dependency>
</dependencies>
    

Read a Page from a Word Document in Java

Using the FixedLayoutDocument class and FixedLayoutPage class makes it easy to extract content from a specified page. To facilitate viewing the extracted content, the following example code saves the extracted content to a new Word document. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain a FixedLayoutPage object for a page in the document.
  • Use the FixedLayoutPage.getSection() method to get the section where the page is located.
  • Get the index position of the first paragraph on the page within the section.
  • Get the index position of the last paragraph on the page within the section.
  • Create another Document object.
  • Add a new section using Document.addSection().
  • Clone the properties of the original section to the new section using Section.cloneSectionPropertiesTo(newSection) method.
  • Copy the content of the page from the original document to the new document.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.pages.*;
import com.spire.doc.documents.*;

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

        // Load document content from the specified file
        document.loadFromFile("Sample.docx");

        // Create a fixed layout document object
        FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

        // Get the first page
        FixedLayoutPage page = layoutDoc.getPages().get(0);

        // Get the section where the page is located
        Section section = page.getSection();

        // Get the first paragraph of the page
        Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph();
        int startIndex = 0;
        if (paragraphStart != null) {
            // Get the index of the paragraph in the section
            startIndex = section.getBody().getChildObjects().indexOf(paragraphStart);
        }

        // Get the last paragraph of the page
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        int endIndex = 0;
        if (paragraphEnd != null) {
            // Get the index of the paragraph in the section
            endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd);
        }

        // Create a new document object
        Document newdoc = new Document();

        // Add a new section
        Section newSection = newdoc.addSection();

        // Clone the properties of the original section to the new section
        section.cloneSectionPropertiesTo(newSection);

        // Copy the content of the original document's page to the new document
        for (int i = startIndex; i <=endIndex; i++)
        {
            newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone());
        }

        // Save the new document to the specified file
        newdoc.saveToFile("Content of One Page.docx", FileFormat.Docx);

        // Close and release the new document
        newdoc.close();
        newdoc.dispose();

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

Java: Read Content from a Word Document

Read a Section from a Word Document in Java

Using Document.Sections[index], you can access specific Section objects that contain the header, footer, and body content of a document. The following example demonstrates a simple method to copy all content from one section to another document. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Use Document.getSections().get(1) to retrieve the second section of the document.
  • Create another new Document object.
  • Clone the default style of the original document to the new document using Document.cloneDefaultStyleTo(newdoc) method.
  • Use Document.getSections().add(section.deepClone()) to clone the content of the second section of the original document to the new document.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;

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

        // Load a Word document from a file
        document.loadFromFile("Sample.docx");

        // Get the second section of the document
        Section section = document.getSections().get(1);

        // Create a new document object
        Document newdoc = new Document();

        // Clone the default style to the new document
        document.cloneDefaultStyleTo(newdoc);

        // Clone the second section to the new document
        newdoc.getSections().add(section.deepClone());

        // Save the new document to a file
        newdoc.saveToFile("Content of One Section.docx", FileFormat.Docx);

        // Close and release the new document object
        newdoc.close();
        newdoc.dispose();

        // Close and release the original document object
        document.close();
        document.dispose();
    }
}

Java: Read Content from a Word Document

Read the Entire Content from a Word Document in Java

This example demonstrates how to iterate through each section of the original document to read the entire content of the document and clone each section into a new document. This method can help you quickly replicate both the structure and content of the entire document, preserving the format and layout of the original document in the new document. Such operations are very useful for maintaining the integrity and consistency of the document structure. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create another new Document object.
  • Clone the default style of the original document to the new document using the Document.cloneDefaultStyleTo(newdoc) method.
  • Iterate through each section of the original document using a for loop and clone it into the new document.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;

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

        // Load a Word document from a file
        document.loadFromFile("Sample.docx");

        // Create a new document object
        Document newdoc = new Document();

        // Clone the default style to the new document
        document.cloneDefaultStyleTo(newdoc);

        // Iterate through each section in the original document and clone it to the new document
        for (Section sourceSection : (Iterable) document.getSections()) {
            newdoc.getSections().add(sourceSection.deepClone());
        }

        // Save the new document to a file
        newdoc.saveToFile("Content of the entire document.docx", FileFormat.Docx);

        // Close and release the new document object
        newdoc.close();
        newdoc.dispose();

        // Close and release the original document object
        document.close();
        document.dispose();
    }
}

Java: Read Content from a Word Document

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.

Adding, inserting, and deleting pages in a Word document are crucial steps in managing and presenting content. By adding or inserting new pages, you can expand the document to accommodate more content, making it more organized and readable. Deleting pages helps simplify the document by removing unnecessary or erroneous information. These operations can enhance the overall quality and clarity of the document. This article will demonstrate how to use Spire.Doc for Java to add, insert, and delete pages in a Word document 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.4.6</version>
    </dependency>
</dependencies>
    

Add a Page in a Word Document in Java

The steps to add a new page at the end of a Word document include locating the last section, and then inserting a page break at the end of that section's last paragraph. This way ensures that any content added subsequently will start displaying on a new page, maintaining the clarity and coherence of the document structure. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Get the body of the last section of the document using Document.getLastSection().getBody().
  • Add a page break by calling Paragraph.appendBreak(BreakType.Page_Break) method.
  • Create a new paragraph style ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.getStyles().add(paragraphStyle) method.
  • Create a new paragraph Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using Paragraph.applyStyle(paragraphStyle.getName()) method.
  • Add the new paragraph to the document using Body.getChildObjects().add(paragraph) method.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;

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

        // Load a sample document from a file
        document.loadFromFile("Sample.docx");

        // Get the body of the last section of the document
        Body body = document.getLastSection().getBody();

        // Insert a page break after the last paragraph in the body
        body.getLastParagraph().appendBreak(BreakType.Page_Break);

        // Create a new paragraph style
        ParagraphStyle paragraphStyle = new ParagraphStyle(document);
        paragraphStyle.setName("CustomParagraphStyle1");
        paragraphStyle.getParagraphFormat().setLineSpacing(12);
        paragraphStyle.getParagraphFormat().setAfterSpacing(8);
        paragraphStyle.getCharacterFormat().setFontName("Microsoft YaHei");
        paragraphStyle.getCharacterFormat().setFontSize(12);

        // Add the paragraph style to the document's style collection
        document.getStyles().add(paragraphStyle);

        // Create a new paragraph and set the text content
        Paragraph paragraph = new Paragraph(document);
        paragraph.appendText("Thank you for using our Spire.Doc for Java product. The trial version will add a red watermark to the generated result document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add the paragraph to the body's content collection
        body.getChildObjects().add(paragraph);

        // Create another new paragraph and set the text content
        paragraph = new Paragraph(document);
        paragraph.appendText("To fully experience our product, we provide a one-month temporary license for each of our customers for free. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add the paragraph to the body's content collection
        body.getChildObjects().add(paragraph);

        // Save the document to a specified path
        document.saveToFile("Add a Page.docx", FileFormat.Docx);

        // Close the document
        document.close();

        // Dispose of the document object's resources
        document.dispose();
    }
}

Java Add, Insert, or Delete Pgaes in Word Documents

Insert a Page in a Word Document in Java

Before inserting a new page, it is necessary to determine the ending position index of the specified page content within the section, and then add the content of the new page to the document one by one. To ensure that the content is separated from the subsequent pages, page breaks need to be inserted at appropriate positions. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of a page in the document.
  • Get the index position of the last paragraph on the page within the section.
  • Create a new paragraph style ParagraphStyle object.
  • Add the new paragraph style to the document using the Document.getStyles().add(paragraphStyle) method.
  • Create a new paragraph Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using the Paragraph.applyStyle(paragraphStyle.getName()) method.
  • Insert the new paragraph at the specified position using the Body.getChildObjects().insert(index, Paragraph) method.
  • Create another new paragraph object, set its text content, add a page break by calling the Paragraph.appendBreak(BreakType.Page_Break) method, apply the previously created paragraph style, and finally insert this paragraph into the document.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.pages.*;
import com.spire.doc.documents.*;

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

        // Load a sample document from a file
        document.loadFromFile("Sample.docx");

        // Create a fixed layout document object
        FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

        // Get the first page
        FixedLayoutPage page = layoutDoc.getPages().get(0);

        // Get the body of the document
        Body body = page.getSection().getBody();

        // Get the paragraph at the end of the current page
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        // Initialize the end index
        int endIndex = 0;
        if (paragraphEnd != null) {
            // Get the index of the last paragraph
            endIndex = body.getChildObjects().indexOf(paragraphEnd);
        }

        // Create a new paragraph style
        ParagraphStyle paragraphStyle = new ParagraphStyle(document);
        paragraphStyle.setName("CustomParagraphStyle1");
        paragraphStyle.getParagraphFormat().setLineSpacing(12);
        paragraphStyle.getParagraphFormat().setAfterSpacing(8);
        paragraphStyle.getCharacterFormat().setFontName("Microsoft YaHei");
        paragraphStyle.getCharacterFormat().setFontSize(12);

        // Add the style to the document
        document.getStyles().add(paragraphStyle);

        // Create a new paragraph and set the text content
        Paragraph paragraph = new Paragraph(document);
        paragraph.appendText("Thank you for using our Spire.Doc for Java product. The trial version will add a red watermark to the generated result document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Insert the paragraph at the specified position
        body.getChildObjects().insert(endIndex + 1, paragraph);

        // Create another new paragraph and set the text content
        paragraph = new Paragraph(document);
        paragraph.appendText("To fully experience our product, we provide a one-month temporary license for each of our customers for free. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add a page break
        paragraph.appendBreak(BreakType.Page_Break);

        // Insert the paragraph at the specified position
        body.getChildObjects().insert(endIndex + 2, paragraph);

        // Save the document to a specified path
        document.saveToFile("Insert a New Page after a Specified Page.docx", FileFormat.Docx);

        // Close and dispose of the document object's resources
        document.close();
        document.dispose();
    }
}

Java Add, Insert, or Delete Pgaes in Word Documents

Delete a Page from a Word Document in Java

To delete the content of a page, you first need to find the position index of the starting and ending elements of that page in the document. Then, by looping through, you can remove these elements one by one to delete the entire content of the page. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of the first page in the document.
  • Use the FixedLayoutPage.getSection() method to get the section where the page is located.
  • Get the index position of the first paragraph on the page within the section.
  • Get the index position of the last paragraph on the page within the section.
  • Use a for loop to remove the content of the page one by one.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.pages.*;
import com.spire.doc.documents.*;

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

        // Load a sample document from a file
        document.loadFromFile("Sample.docx");

        // Create a fixed layout document object
        FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

        // Get the second page
        FixedLayoutPage page = layoutDoc.getPages().get(1);

        // Get the section of the page
        Section section = page.getSection();

        // Get the first paragraph on the first page
        Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph();
        int startIndex = 0;
        if (paragraphStart != null) {
            // Get the index of the starting paragraph
            startIndex = section.getBody().getChildObjects().indexOf(paragraphStart);
        }

        // Get the last paragraph on the last page
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        int endIndex = 0;
        if (paragraphEnd != null) {
            // Get the index of the ending paragraph
            endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd);
        }

        // Remove paragraphs within the specified range
        for (int i = 0; i <= (endIndex - startIndex); i++) {
            section.getBody().getChildObjects().removeAt(startIndex);
        }

        // Save the document to a specified path
        document.saveToFile("Delete a Page.docx", FileFormat.Docx);

        // Close and dispose of the document object's resources
        document.close();
        document.dispose();
    }
}

Java Add, Insert, or Delete Pgaes 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.

Captions play multiple important roles in a document. They not only provide explanations for images or tables but also help in organizing the document structure, referencing specific content, and ensuring consistency and standardization. They serve as guides, summaries, and emphasis within the document, enhancing readability and assisting readers in better understanding and utilizing the information presented in the document. This article will demonstrate how to use Spire.Doc for Java to add or remove captions 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.4.6</version>
    </dependency>
</dependencies>
    

Add Image Captions to a Word document in Java

By using the DocPicture.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, you can easily add descriptive captions to images within a Word document. The following are the detailed steps:

  • Create an object of the Document class.
  • Use the Document.addSection() method to add a section.
  • Add a paragraph using Section.addParagraph() method.
  • Use the Paragraph.appendPicture(String filePath) method to add a DocPicture image object to the paragraph.
  • Add a caption using the DocPicture.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, numbering the captions in CaptionNumberingFormat.Number format.
  • Update all fields using the Document.isUpdateFields(true) method.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class addPictureCaption {
    public static void main(String[] args) {

        // Create a Word document object
        Document document = new Document();

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

        // Add a new paragraph and insert an image into it
        Paragraph pictureParagraphCaption = section.addParagraph();
        pictureParagraphCaption.getFormat().setAfterSpacing(10);
        DocPicture pic1 = pictureParagraphCaption.appendPicture("Data\\1.png");
        pic1.setHeight(100);
        pic1.setWidth(100);

        // Add a caption to the image
        CaptionNumberingFormat format = CaptionNumberingFormat.Number;
        pic1.addCaption("Image", format, CaptionPosition.Below_Item);

        // Add another paragraph and insert another image into it
        pictureParagraphCaption = section.addParagraph();
        DocPicture pic2 = pictureParagraphCaption.appendPicture("Data\\2.png");
        pic2.setHeight(100);
        pic2.setWidth(100);

        // Add a caption to the second image
        pic2.addCaption("Image", format, CaptionPosition.Below_Item);

        // Update all fields in the document
        document.isUpdateFields(true);

        // Save the document as a docx file
        String result = "AddImageCaption.docx";
        document.saveToFile(result, FileFormat.Docx_2016);

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

Java: Add or Remove Captions in Word documents

Add Table Captions to a Word document in Java

Similar to adding captions to images, to add a caption to a table, you need to call the Table.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method. The detailed steps are as follows:

  • Create an object of the Document class.
  • Use the Document.addSection() method to add a section.
  • Create a Table object and add it to the specified section in the document.
  • Use the Table.resetCells(int rowsNum, int columnsNum) method to set the number of rows and columns in the table.
  • Add a caption using the Table.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, numbering the captions in CaptionNumberingFormat.Number format.
  • Update all fields using the Document.isUpdateFields(true) method.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
public class addTableCaption {
    public static void main(String[] args) {

        // Create a Word document object
        Document document = new Document();

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

        // Add a table to the section
        Table tableCaption = section.addTable(true);
        tableCaption.resetCells(3, 2);

        // Add a caption to the table
        tableCaption.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);

        // Add another table to the section
        tableCaption = section.addTable(true);
        tableCaption.resetCells(2, 3);

        // Add a caption to the second table
        tableCaption.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);

        // Update all fields in the document
        document.isUpdateFields(true);

        // Save the document as a docx file
        String result = "AddTableCaption.docx";
        document.saveToFile(result, FileFormat.Docx_2016);

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

Java: Add or Remove Captions in Word documents

Remove Captions from a Word document in Java

In addition to adding captions, Spire.Doc for Java also supports deleting captions from a Word document. The steps involved are as follows:

  • Create an object of the Document class.
  • Use the Document.loadFromFile() method to load a Word document.
  • Create a custom method named DetectCaptionParagraph(Paragraph paragraph), to determine if the paragraph contains a caption.
  • Iterate through all the Paragraph objects in the document using a loop and use the custom method, DetectCaptionParagraph(Paragraph paragraph), to identify the paragraphs that contain captions and delete them.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

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

        // Create a Word document object
        Document document = new Document();

        // Load the sample.docx file
        document.loadFromFile("Data/sample.docx");

        Section section;

        // Iterate through all sections
        for (int i = 0; i < document.getSections().getCount(); i++) {
            section = document.getSections().get(i);

        // Iterate through paragraphs in reverse order
            for (int j = section.getBody().getParagraphs().getCount() - 1; j >= 0; j--) {
                // Check if the paragraph is a caption paragraph
                if (DetectCaptionParagraph(section.getBody().getParagraphs().get(j))) {
                    // If it is a caption paragraph, remove it
                    section.getBody().getParagraphs().removeAt(j);
                }
            }
        }

        // Save the document after removing captions
        String result = "RemoveCaptions.docx";
        document.saveToFile(result, FileFormat.Docx_2016);

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

    // Method to detect if a paragraph is a caption paragraph
    static Boolean DetectCaptionParagraph(Paragraph paragraph) {
        Boolean tag = false;
        Field field;

        // Iterate through child objects of the paragraph
        for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {
            if (paragraph.getChildObjects().get(i).getDocumentObjectType().equals(DocumentObjectType.Field)) {
                // Check if the child object is of type Field
                field = (Field) paragraph.getChildObjects().get(i);
                if (field.getType().equals(FieldType.Field_Sequence)) {
                    // Check if the Field type is FieldSequence, indicating a caption field
                    return true;
                }
            }
        }

        return tag;
    }
}

Java: Add or Remove Captions 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.

Java: Extract Text from HTML

2023-08-29 01:53:40 Written by support iceblue

HTML (Hypertext Markup Language) has become one of the most commonly used text markup languages on the Internet, and nearly all web pages are created using HTML. While HTML contains numerous tags and formatting information, the most valuable content is typically the visible text. It is important to know how to extract the text content from an HTML file when users intend to utilize it for tasks such as editing, AI training, or storing in databases. This article will demonstrate how to extract text from HTML using Spire.Doc for Java within Java programs.

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

Extract Text from HTML File

Spire.Doc for Java supports loading HTML files using the Document.loadFromFile(fileName, FileFormat.Html) method. Then, users can use Document.getText() method to get the text that is visible in browsers and write it to a TXT file. The detailed steps are as follows:

  • Create an object of Document class.
  • Load an HTML file using Document.loadFromFile(fileName, FileFormat.Html) method.
  • Get the text of the HTML file using Document.getText() method.
  • Write the text to a TXT file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.io.FileWriter;
import java.io.IOException;

public class ExtractTextFromHTML {
    public static void main(String[] args) throws IOException {

        //Create an object of Document class
        Document doc = new Document();

        //Load an HTML file
        doc.loadFromFile("Sample.html", FileFormat.Html);

        //Get text from the HTML file
        String text = doc.getText();

        //Write the text to a TXT file
        FileWriter fileWriter = new FileWriter("HTMLText.txt");
        fileWriter.write(text);
        fileWriter.close();
    }
}

HTML Web Page:

Java: Extract Text from HTML

Extracted Text:

Java: Extract Text from HTML

Extract Text from URL

To extract text from a URL, users need to create a custom method to retrieve the HTML file from the URL and then extract the text from it. The detailed steps are as follows:

  • Create an object of Document class.
  • Use the custom method readHTML() to get the HTML file from a URL and return the file path.
  • Load the HTML file using Document.loadFromFile(filename, FileFormat.Html) method.
  • Get the text from the HTML file using Document.getText() method.
  • Write the text to a TXT file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class ExtractTextFromURL {
    public static void main(String[] args) throws IOException {
        //Create an object of Document
        Document doc = new Document();

        //Call the custom method to load the HTML file from a URL
        doc.loadFromFile(readHTML("https://aeon.co/essays/how-to-face-the-climate-crisis-with-spinoza-and-self-knowledge", "output.html"), FileFormat.Html);

        //Get the text from the HTML file
        String urlText = doc.getText();

        //Write the text to a TXT file
        FileWriter fileWriter = new FileWriter("URLText.txt");
        fileWriter.write(urlText);
    }

    public static String readHTML(String urlString, String saveHtmlFilePath) throws IOException {

        //Create an object of URL class
        URL url = new URL(urlString);

        //Open the URL
        URLConnection connection = url.openConnection();

        //Save the url as an HTML file
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveHtmlFilePath), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            writer.write(line);
            writer.newLine();
        }

        reader.close();
        writer.close();

        //Return the file path of the saved HTML file
        return saveHtmlFilePath;
    }
}

URL Web Page:

Java: Extract Text from HTML

Extracted Text:

Java: Extract Text from HTML

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.

Repeating watermarks, also called multi-line watermarks, are a type of watermark that appears multiple times on a page of a Word document at regular intervals. Compared with single watermarks, repeating watermarks are more difficult to remove or obscure, thus offering a better deterrent to unauthorized copying and distribution. This article is going to show how to insert repeating text and image watermarks 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.6</version>
    </dependency>
</dependencies>
    

Add Repeating Text Watermarks to Word Documents in Java

We can insert repeating text watermarks to Word documents by adding repeating WordArt to the headers of a document at specified intervals. The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Create an object of ShapeObject class and set the WordArt text using ShapeObject.getWordArt().setText() method.
  • Specify the rotation angle and the number of vertical repetitions and horizontal repetitions.
  • Set the format of the shape using methods under ShapeObject class.
  • Loop through the sections in the document to insert repeating watermarks to each section by adding the WordArt shape to the header of each section multiple times at specified intervals using Paragraph.getChildObjects().add(ShapeObject) method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.HeaderFooter;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ShapeLineStyle;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.fields.ShapeObject;

import java.awt.*;

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

        //Create an object of Document class
        Document doc = new Document();

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

        //Create an object of ShapeObject class and set the WordArt text
        ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
        shape.getWordArt().setText("DRAFT");

        //Specify the watermark rotating angle and the number of vertical repetitions and horizontal repetitions
        double rotation = 315;
        int ver = 5;
        int hor = 3;

        //Set the format of the WordArt shape
        shape.setWidth(60);
        shape.setHeight(20);
        shape.setVerticalPosition(30);
        shape.setHorizontalPosition(20);
        shape.setRotation(rotation);
        shape.setFillColor(Color.BLUE);
        shape.setLineStyle(ShapeLineStyle.Single);
        shape.setStrokeColor(Color.CYAN);
        shape.setStrokeWeight(1);

        //Loop through the sections in the document
        for (Section section : (Iterable) doc.getSections()
        ) {
            //Get the header of a section
            HeaderFooter header = section.getHeadersFooters().getHeader();
            //Add paragraphs to the header
            Paragraph paragraph = header.addParagraph();
            for (int i = 0; i < ver; i++) {
                for (int j = 0; j < hor; j++) {
                    //Add the WordArt shape to the header
                    shape = (ShapeObject) shape.deepClone();
                    shape.setVerticalPosition((float) (section.getPageSetup().getPageSize().getHeight()/ver * i + Math.sin(rotation) * shape.getWidth()/2));
                    shape.setHorizontalPosition((float) ((section.getPageSetup().getPageSize().getWidth()/hor - shape.getWidth()/2) * j));
                    paragraph.getChildObjects().add(shape);
                }
            }
        }

        //Save the document
        doc.saveToFile("RepeatingTextWatermark.docx");
        doc.dispose();
    }
}

Java: Insert Repeating Watermarks into Word Documents

Add Repeating Picture Watermarks to Word Documents in Java

Similarly, we can insert repeating image watermarks into Word documents by adding repeating pictures to headers at regular intervals. The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Load a picture using DocPicture.loadImage() method.
  • Set the text wrapping style of the picture as Behind using DocPicture.setTextWrappingStyle(TextWrappingStyle.Behind) method.
  • Specify the number of vertical repetitions and horizontal repetitions.
  • Loop through the sections in the document to insert repeating picture watermarks to the document by adding a picture to the header of each section at specified intervals using Paragraph.getChildObjects().add(DocPicture) method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.HeaderFooter;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

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

        //Create an object of Document class
        Document doc = new Document();

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

        //Load a picture
        DocPicture pic = new DocPicture(doc);
        pic.loadImage("watermark.png");

        //Set the text wrapping style of the picture as Behind
        pic.setTextWrappingStyle(TextWrappingStyle.Behind);

        //Specify the number of vertical repetitions and horizontal repetitions
        int ver = 4;
        int hor = 3;

        //Loop through the sections in the document
        for (Section section : (Iterable) doc.getSections()
        ) {
            //Get the header of a section
            HeaderFooter header = section.getHeadersFooters().getHeader();
            //Add a paragraph to the section
            Paragraph paragraph = header.addParagraph();
            for (int i = 0; i < ver; i++) {
                for (int j = 0; j < hor; j++) {
                    //Add the picture to the header
                    pic = (DocPicture) pic.deepClone();
                    pic.setVerticalPosition((float) ((section.getPageSetup().getPageSize().getHeight()/ver) * i));
                    pic.setHorizontalPosition((float) (section.getPageSetup().getPageSize().getWidth()/hor - pic.getWidth()/2) * j);
                    paragraph.getChildObjects().add(pic);
                }
            }
        }

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

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

Java: Set the Font in Word

2023-06-09 01:08:10 Written by support iceblue

When it comes to creating professional documents, choosing the right font is crucial. Using multiple fonts in one document can help distinguish different types of content such as headings, body text or annotations, ultimately enhancing the document's readability. Moreover, different fonts have unique emotional tones and styles. For instance, handwritten fonts often convey warmth and intimacy while serif fonts are ideal for traditional and formal contexts. Although Microsoft Word offers a wide range of font capabilities, setting the font programmatically is also necessary. In this article, we will demonstrate how to set the font of Word document in Java using Spire.Doc for Java library.

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

Set the Font in Word

To set different fonts for different paragraphs in a Word document, you need to create multiple paragraph styles and then set a different font for each paragraph style. After that, apply these paragraph styles to specific paragraphs. The detailed steps are as follows:

  • Create a Document instance.
  • Add a section to this document using Document. addSection() method.
  • Add three paragraphs to this section using Section.addParagraph() method, and then use Paragraph.appendText() method to append text for each of them.
  • Create a ParagraphStyle instance.
  • Set the paragraph style name using ParagraphStyle.setName method.
  • Set the font name and size using ParagraphStyle.getCharacterFormat().setFontName() and ParagraphStyle.getCharacterFormat().setFontSize() method.
  • Add the style to the document using Document.getStyles().add() method.
  • Apply the desired paragraph style to the paragraph using the Paragraph.applyStyle() method.
  • Repeat the above steps to create another ParagraphStyle instance, set its font, and  apply it to other paragraphs.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;


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

        //Add a section to this document
        Section section = document.addSection();

        //Add three paragraphs to this section and append text for each of them
        Paragraph para1 = section.addParagraph();
        para1.appendText("Yellowstone National Park");

        Paragraph para2 = section.addParagraph();
        para2.appendText("Yellowstone National Park, or Yellowstone Park for short, is managed by the National Park Service of the United States. On March 1, 1872, it was officially named as a national park to protect wild animals and natural resources, and was included in the World Natural Heritage List in 1978. This is the first national park in the world.");

        Paragraph para3 = section.addParagraph();
        para3.appendText("Yellowstone National Park covers an area of 898317 hectares, mainly located in Wyoming, USA, and partially located in Montana and Idaho. Yellowstone Park is divided into five areas: the Mammoth Hot Spring Area in the northwest is mainly composed of limestone steps, so it is also called hot step area.");

        //Create a ParagraphStyle instance
        ParagraphStyle style1 = new ParagraphStyle(document);

        //Set the first paragraph as the title and set its font
        style1.setName("titleStyle");
        style1.getCharacterFormat().setFontName("Arial");
        style1.getCharacterFormat().setFontSize(16f);
        document.getStyles().add(style1);
        para1.applyStyle("titleStyle");

        //Create a ParagraphStyle instance
        ParagraphStyle style2 = new ParagraphStyle(document);

        //Set the other two paragraphs as the body and set their fonts
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Times New Roman");
        style2.getCharacterFormat().setFontSize(10f);
        document.getStyles().add(style2);
        para2.applyStyle("paraStyle");
        para3.applyStyle("paraStyle");

        //Save the result docunmen
        document.saveToFile("output/setFont.docx", FileFormat.Docx);
        document.dispose();
    }
}

Java: Set the Font 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.

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

Install Spire.Doc for Java

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

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

Insert Variables into Word Documents

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

  • Create an object of Document.
  • Add a section to the document using Document.addSection() method.
  • Add a paragraph to the section using Section.addParagraph() method.
  • Add variable fields to the paragraph using Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) method.
  • Get the variable collection using Document.getVariables() method.
  • Assign a value to the variable using VariableCollection.add() method.
  • Update the fields in the document using Document.isUpdateFields() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.formatting.CharacterFormat;

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

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

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

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

        //Set text format
        CharacterFormat characterFormat = paragraph.getStyle().getCharacterFormat();
        characterFormat.setFontName("Times New Roman");
        characterFormat.setFontSize(14);

        //Set the page margin
        section.getPageSetup().getMargins().setTop(80f);

        //Add variable fields to the paragraph
        paragraph.appendField("Term", FieldType.Field_Doc_Variable);
        paragraph.appendText(" is an object.\r\n");
        paragraph.appendField("Term", FieldType.Field_Doc_Variable);
        paragraph.appendText(" is not a backdrop, an illusion, or an emergent phenomenon.\r\n");
        paragraph.appendField("Term", FieldType.Field_Doc_Variable);
        paragraph.appendText(" has a physical size that be measured in laboratories.");

        //Get the variable collection
        VariableCollection variableCollection = document.getVariables();

        //Assign a value to the variable
        variableCollection.add("Term", "Time");

        //Update the fields in the document
        document.isUpdateFields(true);

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

Java: Add and Change Variables in Word Documents

Change the Value of Variables in Word Documents

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

  • Create an object of Document.
  • Load a Word document using Document.loaFromFile() method.
  • Get the variable collection using Document.getVariables() method.
  • Assign a new value to a specific variable through its name using VariableCollection.set() method.
  • Update the fields in the document using Document.isUpdateFields() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.VariableCollection;

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

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

        //Load a Word document
        document.loadFromFile("AddVariables.docx");

        //Get the variable collection
        VariableCollection variableCollection = document.getVariables();

        //Assign a new value to a variable
        variableCollection.set("Term", "The time");

        //Update the fields in the document
        document.isUpdateFields(true);

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

Java: Add and Change Variables in Word Documents

Apply for a Temporary License

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

A list is an effective way to organize information and present it clearly and logically. The elements in the list stand out from other parts of the text, encouraging readers to pay attention to them. Depending on your requirements, you can add numbered lists, bulleted lists or multi-level lists to your Word documents. This article demonstrates how to create these types of lists in a Word document 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.6</version>
    </dependency>
</dependencies>
    

Insert a Numbered List in Word in Java

Spire.Doc for Java offers the ListStyle class that you can use to create a numbered list style or a bulleted style. Then, the list style can be applied to a paragraph using Paragraph.getListFormat().applyStyle() method. The steps to create a numbered list are as follows.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Create an instance of ListStyle class, specifying the list type to Numbered.
  • Get a specific level of the list using ListStyle.getLevels().get(index) method, and set the numbering type using ListLevel.setPatternType() method.
  • Add the list style to the document using Document.getListStyles().add() method.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.getListFormat().applyStyle() method.
  • Specify the list level using Paragraph.getListFormat().setListLevelNumber() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.ListPatternType;
import com.spire.doc.documents.ListStyle;
import com.spire.doc.documents.ListType;
import com.spire.doc.documents.Paragraph;

public class InsertNumberedList {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

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

        //Create a numbered list style
        ListStyle listStyle = new ListStyle(document, ListType.Numbered);
        listStyle.setName("numberedList");
        listStyle.getLevels().get(0).setPatternType(ListPatternType.Decimal_Half_Width);
        listStyle.getLevels().get(0).setTextPosition(20);
        document.getListStyles().add(listStyle);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Required Web Development Skills:");
        paragraph.getFormat().setAfterSpacing(5);

        //Add a paragraph and apply the numbered list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("HTML");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another four paragraphs and apply the numbered list style to them
        paragraph = section.addParagraph();
        paragraph.appendText("CSS");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("JavaScript");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Python");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("MySQL");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/NumberedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

Insert a Bulleted List in Word in Java

The process of creating a bulleted list is similar to that of creating a numbered list. The difference is that when creating a list style, you must specify the list type as Bulleted and set a bullet symbol for it. The following are the detailed steps.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Create an instance of ListStyle class, specifying the list type to Bulleted.
  • Get a specific level of the list using ListStyle.getLevels().get(index) method, and set the bullet symbol using ListLevel.setBulletCharacter() method.
  • Add the list style to the document using Document.getListStyles().add() method.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.getListFormat().applyStyle() method.
  • Specify the list level using Paragraph.getListFormat().setListLevelNumber() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.ListStyle;
import com.spire.doc.documents.ListType;
import com.spire.doc.documents.Paragraph;

public class InsertBulletedList {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

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

        //Create a bulleted list style
        ListStyle listStyle = new ListStyle(document, ListType.Bulleted);
        listStyle.setName("bulletedList");
        listStyle.getLevels().get(0).setBulletCharacter("\u00B7");
        listStyle.getLevels().get(0).getCharacterFormat().setFontName("Symbol");
        listStyle.getLevels().get(0).setTextPosition(20);
        document.getListStyles().add(listStyle);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Computer Science Subjects:");
        paragraph.getFormat().setAfterSpacing(5);

        //Add a paragraph and apply the bulleted list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("Data Structure");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another five paragraphs and apply the bulleted list style to them
        paragraph = section.addParagraph();
        paragraph.appendText("Algorithm");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Computer Networks");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Operating System");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("C Programming");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Theory of Computations");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/BulletedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

Insert a Multi-Level Numbered List in Word in Java

A multi-level list consists of at least two different levels. Each level of a nested list can be accessed using ListStyle.getLevels().get(index) method. Through ListLevel object, you can set the numbering type and prefix for a certain level. The following are the steps to create a multi-level numbered list in Word.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Create an instance of ListStyle class, specifying the list type to Numbered.
  • Get a specific level of the list using ListStyle.getLevels().get(index) method, and set the numbering type and prefix.
  • Add the list style to the document using Document.getListStyles().add() method.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.getListFormat().applyStyle() method.
  • Specify the list level using Paragraph.getListFormat().setListLevelNumber() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.ListPatternType;
import com.spire.doc.documents.ListStyle;
import com.spire.doc.documents.ListType;
import com.spire.doc.documents.Paragraph;

public class InsertMultilevelNumberedList {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

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

        //Create a numbered list style, specifying number prefix and pattern type of each level
        ListStyle listStyle = new ListStyle(document, ListType.Numbered);
        listStyle.setName("nestedStyle");
        listStyle.getLevels().get(0).setPatternType(ListPatternType.Arabic);
        listStyle.getLevels().get(0).setTextPosition(20);
        listStyle.getLevels().get(1).setNumberPrefix("\u0000.");
        listStyle.getLevels().get(1).setPatternType(ListPatternType.Arabic);
        listStyle.getLevels().get(2).setNumberPrefix("\u0000.\u0001.");
        listStyle.getLevels().get(2).setPatternType(ListPatternType.Arabic);
        document.getListStyles().add(listStyle);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Here's a Multi-Level Numbered List:");
        paragraph.getFormat().setAfterSpacing(5f);

        //Add a paragraph and apply the numbered list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("The first item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another five paragraphs and apply the numbered list stype to them
        paragraph = section.addParagraph();
        paragraph.appendText("The second item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(1);

        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-item");
        paragraph.getListFormat().continueListNumbering();
        paragraph.getListFormat().applyStyle("nestedStyle");

        paragraph = section.addParagraph();
        paragraph.appendText("A sub-sub-item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(2);

        paragraph = section.addParagraph();
        paragraph.appendText("The third item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/MultilevelNumberedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

Insert a Multi-Level Mixed-Type List in Word in Java

In some cases, you may want to mix number and symbol in a multi-level list. To create a mixed-type list, you just need to create a numbered list style and a bulleted list style and apply them to different paragraphs. The detailed steps are as follows.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Create a numbered list style and a bulleted list style.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply different list style to different paragraphs using Paragraph.getListFormat().applyStyle() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.ListPatternType;
import com.spire.doc.documents.ListStyle;
import com.spire.doc.documents.ListType;
import com.spire.doc.documents.Paragraph;

public class InsertMultilevelMixedTypeList {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

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

        //Create a numbered list style
        ListStyle numberedListStyle = new ListStyle(document, ListType.Numbered);
        numberedListStyle.setName("numberedStyle");
        numberedListStyle.getLevels().get(0).setPatternType(ListPatternType.Arabic);
        numberedListStyle.getLevels().get(0).setTextPosition(20);
        numberedListStyle.getLevels().get(1).setPatternType(ListPatternType.Low_Letter);
        document.getListStyles().add(numberedListStyle);

        //Create a bulleted list style
        ListStyle bulletedListStyle = new ListStyle(document, ListType.Bulleted);
        bulletedListStyle.setName("bulletedStyle");
        bulletedListStyle.getLevels().get(2).setBulletCharacter("\u002A");
        bulletedListStyle.getLevels().get(2).getCharacterFormat().setFontName("Symbol");
        document.getListStyles().add(bulletedListStyle);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Here's a Multi-Level Mixed List:");
        paragraph.getFormat().setAfterSpacing(5f);

        //Add a paragraph and apply the numbered list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("The first item");
        paragraph.getListFormat().applyStyle("numberedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another five paragraphs and apply different list stype to them
        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-item");
        paragraph.getListFormat().applyStyle("numberedStyle");
        paragraph.getListFormat().setListLevelNumber(1);

        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-item");
        paragraph.getListFormat().setListLevelNumber(1);
        paragraph.getListFormat().applyStyle("numberedStyle");

        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-sub-item");
        paragraph.getListFormat().applyStyle("bulletedStyle");
        paragraph.getListFormat().setListLevelNumber(2);

        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-sub-item");
        paragraph.getListFormat().applyStyle("bulletedStyle");
        paragraph.getListFormat().setListLevelNumber(2);

        paragraph = section.addParagraph();
        paragraph.appendText("The second item");
        paragraph.getListFormat().applyStyle("numberedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/MultilevelMixedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

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: Convert Word to Excel

2022-12-19 00:59:46 Written by support iceblue

Word and Excel are different from each other in terms of their uses and functioning. Word is used primarily for text documents such as essays, emails, letters, books, resumes, or academic papers where text formatting is essential. Excel is used to save data, make tables and charts and make complex calculations.

It is not recommended to convert a complex Word file to an Excel spreadsheet, because Excel can hardly render contents in the same way as Word. However, if your Word document is mainly composed of tables and you want to analyze the table data in Excel, you can use Spire.Office for Java to convert Word to Excel while maintaining good readability.

Install Spire.Office for Java

First of all, you're required to add the Spire.Office.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.office</artifactId>
        <version>9.3.1</version>
    </dependency>
</dependencies>
    

Convert Word to Excel in Java

This scenario actually uses two libraries in the Spire.Office package. They're Spire.Doc for Java and Spire.XLS for Java. The former is used to read and extract content from a Word document, and the latter is used to create an Excel document and write data in the specific cells. To make this code example easy to understand, we created the following three custom methods that preform specific functions.

  • exportTableInExcel() - Export data from a Word table to specified Excel cells.
  • copyContentInTable() - Copy content from a table cell in Word to an Excel cell.
  • copyTextAndStyle() - Copy text with formatting from a Word paragraph to an Excel cell.

The following steps demonstrate how to export data from a Word document to a worksheet using Spire.Office for Java.

  • Create a Document object to load a Word file.
  • Create a Workbook object and add a worksheet named "WordToExcel" to it.
  • Traverse though all the sections in the Word document, traverse through all the document objects under a certain section, and then determine if a document object is a paragraph or a table.
  • If the document object is a paragraph, write the paragraph in a specified cell in Excel using coypTextAndStyle() method.
  • If the document object is a table, export the table data from Word to Excel cells using exportTableInExcel() method.
  • Auto fit the row height and column width in Excel so that the data within a cell will not exceed the bound of the cell.
  • Save the workbook to an Excel file using Workbook.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;

import java.awt.*;

public class ConvertWordToExcel {

    public static void main(String[] args) {

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

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

        //Create a Workbook object
        Workbook wb = new Workbook();

        //Remove the default worksheets
        wb.getWorksheets().clear();

        //Create a worksheet named "WordToExcel"
        Worksheet worksheet = wb.createEmptySheet("WordToExcel");
        int row = 1;
        int column = 1;

        //Loop through the sections in the Word document
        for (int i = 0; i < doc.getSections().getCount(); i++) {
            //Get a specific section
            Section section = doc.getSections().get(i);

            //Loop through the document object under a certain section
            for (int j = 0; j < section.getBody().getChildObjects().getCount(); j++) {
                //Get a specific document object
                DocumentObject documentObject = section.getBody().getChildObjects().get(j);

                //Determine if the object is a paragraph
                if (documentObject instanceof Paragraph) {
                    CellRange cell = worksheet.getCellRange(row, column);
                    Paragraph paragraph = (Paragraph) documentObject;
                    //Copy paragraph from Word to a specific cell
                    copyTextAndStyle(cell, paragraph);
                    row++;
                }

                //Determine if the object is a table
                if (documentObject instanceof Table) {
                    Table table = (Table) documentObject;
                    //Export table data from Word to Excel
                    int currentRow = exportTableInExcel(worksheet, row, table);
                    row = currentRow;
                }
            }
        }

        //Wrap text in cells
        worksheet.getAllocatedRange().isWrapText(true);

        //Auto fit row height and column width
        worksheet.getAllocatedRange().autoFitRows();
        worksheet.getAllocatedRange().autoFitColumns();
        
        //Save the workbook to an Excel file
        wb.saveToFile("output/WordToExcel.xlsx", ExcelVersion.Version2013);
    }

    //Export data from Word table to Excel cells
    private static int exportTableInExcel(Worksheet worksheet, int row, Table table) {
        CellRange cell;
        int column;
        for (int i = 0; i < table.getRows().getCount(); i++) {
            column = 1;
            TableRow tbRow = table.getRows().get(i);
            for (int j = 0; j < tbRow.getCells().getCount(); j++) {
                TableCell tbCell = tbRow.getCells().get(j);
                cell = worksheet.getCellRange(row, column);
                cell.borderAround(LineStyleType.Thin, Color.BLACK);
                copyContentInTable(tbCell, cell);
                column++;
            }
            row++;
        }
        return row;
    }

    //Copy content from a Word table cell to an Excel cell
    private static void copyContentInTable(TableCell tbCell, CellRange cell) {
        Paragraph newPara = new Paragraph(tbCell.getDocument());
        for (int i = 0; i < tbCell.getChildObjects().getCount(); i++) {
            DocumentObject documentObject = tbCell.getChildObjects().get(i);
            if (documentObject instanceof Paragraph) {
                Paragraph paragraph = (Paragraph) documentObject;
                for (int j = 0; j < paragraph.getChildObjects().getCount(); j++) {
                    DocumentObject cObj = paragraph.getChildObjects().get(j);
                    newPara.getChildObjects().add(cObj.deepClone());
                }
                if (i < tbCell.getChildObjects().getCount() - 1) {
                    newPara.appendText("\n");
                }
            }
        }
        copyTextAndStyle(cell, newPara);
    }

    //Copy text and style of a paragraph to a cell
    private static void copyTextAndStyle(CellRange cell, Paragraph paragraph) {

        RichText richText = cell.getRichText();
        richText.setText(paragraph.getText());
        int startIndex = 0;
        for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {
            DocumentObject documentObject = paragraph.getChildObjects().get(i);
            if (documentObject instanceof TextRange) {
                TextRange textRange = (TextRange) documentObject;
                String fontName = textRange.getCharacterFormat().getFontName();
                boolean isBold = textRange.getCharacterFormat().getBold();
                Color textColor = textRange.getCharacterFormat().getTextColor();
                float fontSize = textRange.getCharacterFormat().getFontSize();
                String textRangeText = textRange.getText();
                int strLength = textRangeText.length();
                ExcelFont font = new ExcelFont(cell.getWorksheet().getWorkbook().createFont());
                font.setColor(textColor);
                font.isBold(isBold);
                font.setSize(fontSize);
                font.setFontName(fontName);
                int endIndex = startIndex + strLength;
                richText.setFont(startIndex, endIndex, font);
                startIndex += strLength;
            }
            if (documentObject instanceof DocPicture) {
                DocPicture picture = (DocPicture) documentObject;
                cell.getWorksheet().getPictures().add(cell.getRow(), cell.getColumn(), picture.getImage());
                cell.getWorksheet().setRowHeightInPixels(cell.getRow(), 1, picture.getImage().getHeight());
            }
        }
        switch (paragraph.getFormat().getHorizontalAlignment()) {
            case Left:
                cell.setHorizontalAlignment(HorizontalAlignType.Left);
                break;
            case Center:
                cell.setHorizontalAlignment(HorizontalAlignType.Center);
                break;
            case Right:
                cell.setHorizontalAlignment(HorizontalAlignType.Right);
                break;
        }
    }
}

Java: Convert Word to Excel

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 1 of 9