The following code snippets demonstrate how to indent paragraphs for Word document in Java applications. With the help of Spire.Doc for Java, developers can set the paragraph indentation easily. There are four kinds of paragraph indentation style for word document: Left Indentation, Right Indentation, First Line Indentation and Hanging Indentation.

import com.spire.doc.*;
import com.spire.doc.documents.*;

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

        //load the sample document
        Document document= new Document();
        document.loadFromFile("Sample.docx");

        Section section = document.getSections().get(0);

        //get the second paragraph and set the left indent
        Paragraph para1 = section.getParagraphs().get(1);
        para1.getFormat().setLeftIndent(30);

        //get the third paragraph and set the right indent
        Paragraph para2 = section.getParagraphs().get(2);
        para2.getFormat().setRightIndent(30);

        //get the fourth paragraph and set the first line indent
        Paragraph para3 = section.getParagraphs().get(3);
        para3.getFormat().setFirstLineIndent(40);

        //get the fifth paragraph and set the hanging indent
        Paragraph para4 = section.getParagraphs().get(4);
        para4.getFormat().setFirstLineIndent(-40);
        
        //save the document to file
        document.saveToFile("out/WordIndent.docx", FileFormat.Docx_2013);

    }
}

Effective screenshot after setting the word indentation styles for word paragraph:

Java set paragraph indentation for word document

This article is going to demonstrate how to work with comment in a Word document using Spire.Doc for Java. Spire.Doc supports to add new comment to word document and insert a comment as a reply to a selected comment, it also supports to delete the existing comment from a word document in Java applications.

Add a new comment to word document

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.Comment;


public class WordComment {
    public static void main(String[] args) throws Exception{

            String inputFile="Sample.docx";
            String outputFile="out/Comment.docx";

            //load a word document
            Document document= new Document(inputFile);

            Section section = document.getSections().get(0);
            Paragraph paragraph = section.getParagraphs().get(1);

            //Insert a new comment
            Comment comment = paragraph.appendComment("Spire.Doc for Java");
            comment.getFormat().setAuthor("E-iceblue");
            comment.getFormat().setInitial("CM");

            //save the file
            document.saveToFile(outputFile, FileFormat.Docx);
        }
    }

Java add, delete and reply to comment on word document

Java reply to a comment

import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.doc.fields.*;

public class WordComment {
    public static void main(String[] args) throws Exception{

            String inputFile="Sample.docx";
            String outputFile="out/ReplaytoComment.docx";

            //load a word document
            Document document= new Document(inputFile);

            Comment comment1 = document.getComments().get(0);

            Comment replyComment1 = new Comment(document);

            replyComment1.getFormat().setAuthor("E-iceblue");
            replyComment1.getBody().addParagraph().appendText("Spire.Doc for Java is a professional Word Java library on operating Word documents.");

            //add the new comment as a reply to the selected comment.
            comment1.replyToComment(replyComment1);
            //save the file
            document.saveToFile(outputFile, FileFormat.Docx);
        }
    }

Java add, delete and reply to comment on word document

Delete comment

import com.spire.doc.*;
import com.spire.doc.FileFormat;

public class WordComment{
    public static void main(String[] args) throws Exception{

            String inputFile="Sample.docx";
            String outputFile="out/DeleteComment.docx";

            //load a word document
            Document document= new Document(inputFile);

            //remove the second comment
            document.getComments().removeAt(1);

            //save the file.
            document.saveToFile(outputFile, FileFormat.Docx);
        }
    }

Java add, delete and reply to comment on word document

Tuesday, 14 May 2019 05:57

Insert Shapes in Word in Java

This article demonstrates how to add various kinds of shapes and how to group shapes in a Word document using Spire.Doc for Java.

Insert Shapes

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;

import java.awt.*;

public class InsertShapes {

    public static void main(String[] args) throws Exception {

        //create a Word document.
        Document doc = new Document();

        //add a section and a paragraph
        Section sec = doc.addSection();
        Paragraph para = sec.addParagraph();

        //insert a rectangle
        ShapeObject rectangle = para.appendShape(130, 80, ShapeType.Rectangle);
        rectangle.setFillColor(Color.darkGray);
        rectangle.setStrokeColor(Color.darkGray);
        rectangle.setVerticalPosition(50);

        //insert a triangle
        ShapeObject triangle = para.appendShape((float)(160/Math.sqrt(3)),80, ShapeType.Triangle);
        triangle.setStrokeColor(Color.red);
        triangle.setFillColor(Color.orange);
        triangle.setVerticalPosition(50);
        triangle.setHorizontalPosition(200);

        //insert a ellipse
        ShapeObject circle = para.appendShape(80,80, ShapeType.Ellipse);
        circle.setFillColor(Color.RED);
        circle.setStrokeWeight(15);
        circle.setVerticalPosition(50);
        circle.setHorizontalPosition((float)(270 + 160/Math.sqrt(3)));

        //save to file
        doc.saveToFile("output/InsertShapes.docx", FileFormat.Docx);
    }

}

Insert Shapes in Word in Java

Insert Shape Group

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.fields.ShapeGroup;
import com.spire.doc.fields.ShapeObject;

import java.awt.*;

public class InsertShapeGroup {

    public static void main(String[] args) {

        //create a Word document
        Document doc = new Document();

        //add a section and a paragraph
        Section sec = doc.addSection();
        Paragraph para = sec.addParagraph();

        //get page width
        float pageWidth = sec.getPageSetup().getClientWidth();

        //add a shape group, specifying width, height and horizontal position
        ShapeGroup shapegroup = para.appendShapeGroup(200, 150);
        shapegroup.setHorizontalPosition((pageWidth - 200) / 2);

        //calculate the scale ratio
        float X = (shapegroup.getWidth() / 1000.0f);
        float Y = (shapegroup.getHeight() / 1000.0f);

        //create a circle
        ShapeObject circle_1 = new ShapeObject(doc, ShapeType.Ellipse);
        circle_1.setWidth(80 / X);
        circle_1.setHeight(80 / Y);
        circle_1.setFillColor(new Color(176, 196, 222));
        circle_1.setStrokeColor(new Color(176, 196, 222));
        circle_1.setHorizontalPosition(60 / X);//set its horizontal position relative to shape group
        
        //add the circle to shape group
        shapegroup.getChildObjects().add(circle_1);

        //add two more circles to shape group
        ShapeObject circle_2 = new ShapeObject(doc, ShapeType.Ellipse);
        circle_2.setWidth(80 / X);
        circle_2.setHeight(80 / Y);
        circle_2.setFillColor(new Color(0, 128, 128));
        circle_2.setStrokeColor(new Color(0, 128, 128));
        circle_2.setHorizontalPosition(30 / X);
        circle_2.setVerticalPosition(50 / Y);
        shapegroup.getChildObjects().add(circle_2);
        ShapeObject circle_3 = new ShapeObject(doc, ShapeType.Ellipse);
        circle_3.setWidth(80 / X);
        circle_3.setHeight(80 / Y);
        circle_3.setFillColor(new Color(72, 61, 139));
        circle_3.setStrokeColor(new Color(72, 61, 139));
        circle_3.setHorizontalPosition(90 / X);
        circle_3.setVerticalPosition(50 / Y);
        shapegroup.getChildObjects().add(circle_3);
        
        //save the document
        doc.saveToFile("output/InsertShapeGroup.docx", FileFormat.Docx_2010);
    }
}

Insert Shapes in Word in Java

This article demonstrates how to replace text with new text in a Word document using Spire.Doc for Java.

We can replace a specified text with new text by using the replace method of the Document class:

import com.spire.doc.*;

public class ReplaceText {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document("Input.docx");
        
        //Replace the specified text with new text 
        document.replace("Spire.Doc for Java", "NewText", false, true);
        
        //Save the document
        document.saveToFile("ReplaceAllMatchedText.docx", FileFormat.Docx_2013);
    }
}

Replace Text with New Text in Word in Java

The above example replaces all of the "Spire.Doc for Java" text that exists in the Word document. We can also specify to replace only the first occurrence of the specified text by using the setReplaceFirst method of Document class:

import com.spire.doc.*;

public class ReplaceText {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document("Input.docx");
        
        //Set to replace only the first occurrence of the specified text
        document.setReplaceFirst(true);

        //Replace with new text
        document.replace("Spire.Doc for Java", "NewText", false, true);
        
        //Save the document
        document.saveToFile("ReplaceFirstMatchedText.docx", FileFormat.Docx_2013);
    }
}

Replace Text with New Text in Word in Java

This article demonstrates how to find and highlight text in a Word document using Spire.Doc for Java.

In Spire.Doc for Java, there are two methods can be used to find and highlight text in a Word document: findString() and findAllString(). The findString() method finds the first matched text, while the findAllString() method finds all of the matched text. The below example shows how to find all of the matched text using findAllString() method and then highlight the text.

import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;

import java.awt.*;

public class FindAndHightText {
    public static void main(String[] args){
        //Load Word document
        Document document = new Document("Input.docx");

        //Find all “Spire.Doc for Java” text
        TextSelection[] textSelections = document.findAllString("Spire.Doc for Java", false, true);

        //Set highlight color
        for (TextSelection selection : textSelections) {
            selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
        }

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

Output:

Find and Highlight Text in Word in Java

This article demonstrates how to extract text and images from Word documents by using Spire.Doc for Java.

Extract Text

import com.spire.doc.Document;

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

public class ExtractText {

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

        //load Word document
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //get text from document as string
        String text=document.getText();

        //write string to a .txt file
        writeStringToTxt(text," ExtractedText.txt");
    }

    public static void writeStringToTxt(String content, String txtFileName) throws IOException{

        FileWriter fWriter= new FileWriter(txtFileName,true);
        try {
            fWriter.write(content);
        }catch(IOException ex){
            ex.printStackTrace();
        }finally{
            try{
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Extract Text and Images from Word in Java

Extract Images

import com.spire.doc.Document;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.interfaces.ICompositeObject;
import com.spire.doc.interfaces.IDocumentObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class ExtractImages {

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

        //load word document
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //create a Queue object
        Queue nodes = new LinkedList();
        nodes.add(document);

        //create a List object
        List images = new ArrayList();

        //loop through the child objects of the document
        while (nodes.size() > 0) {
            ICompositeObject node = nodes.poll();
            for (int i = 0; i < node.getChildObjects().getCount(); i++) {
                IDocumentObject child = node.getChildObjects().get(i);
                if (child instanceof ICompositeObject) {
                    nodes.add((ICompositeObject) child);

                    //get each image and add it to the list
                    if (child.getDocumentObjectType() == DocumentObjectType.Picture) {
                        DocPicture picture = (DocPicture) child;
                        images.add(picture.getImage());
                    }
                }
            }
        }

        //save images as .png files
        for (int i = 0; i < images.size(); i++) {
            File file = new File(String.format("output/ExtractedImage-%d.png", i));
            ImageIO.write(images.get(i), "PNG", file);
        }
    }
}

Extract Text and Images from Word in Java

The following code snippets demonstrate how to use Spire.Doc for Java to set the page margins and page borders for word document in Java applications.

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class PageSetup{
    public static void main(String[] args) throws Exception{

            String inputFile="Sample.docx";
            String outputFile="out/result.docx";

            //load a word document
            Document document= new Document(inputFile);

            Section section = document.getSections().get(0);

            //set the page margins
            section.getPageSetup().getMargins().setTop(30f);
            section.getPageSetup().getMargins().setBottom(30f);
            section.getPageSetup().getMargins().setLeft(60f);
            section.getPageSetup().getMargins().setRight(80f);

            //set the boarder type and color
            section.getPageSetup().getBorders().setBorderType(BorderStyle.Double_Wave);
            section.getPageSetup().getBorders().setColor(java.awt.Color.blue);

            //set the space between the border and text
            section.getPageSetup().getBorders().getTop().setSpace(20);
            section.getPageSetup().getBorders().getBottom().setSpace(30);
            section.getPageSetup().getBorders().getLeft().setSpace(30);
            section.getPageSetup().getBorders().getRight().setSpace(25);

            //save the file
            document.saveToFile(outputFile, FileFormat.Docx);
        }

    }

Effective screenshot after setting the page margins and page borders for the word document:

Java set page margins and page borders for word document

Wednesday, 01 May 2019 07:44

Insert Image into Word Document in Java

This article is going to demonstrate how to insert image into a Word document using Spire.Doc for Java.

In Spire.Doc for Java, the appendPicture() method in Paragraph class is used for appending images to Word paragraph. When appending an image, we can customize the image settings like width and height. The image can be from a local file, a byte array or a stream.

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.fields.DocPicture;

import java.awt.*;

public class InsertImage {
    public static void main(String[] args){
        //Create a Document object
        Document doc = new Document();
        //Add a section
        Section section = doc.addSection();

        //Add a paragraph to the section
        Paragraph paragraph1 = section.addParagraph();
        //Set paragraph text
        paragraph1.setText("Insert Image Demo by Spire.Doc for Java");

        //Add another paragraph to the section
        Paragraph paragraph2 = section.addParagraph();
        //Append an image from local file to the paragraph
        DocPicture picture = paragraph2.appendPicture("C:\\Users\\Administrator\\Desktop\\Hydrangeas.jpg");
        //Set image width
        picture.setWidth(300f);
        //Set image height
        picture.setHeight(250f);

        //Apply style to paragraph 1
        ParagraphStyle style = new ParagraphStyle(doc);
        style.setName("titleStyle");
        style.getCharacterFormat().setBold(true);
        style.getCharacterFormat().setTextColor(Color.BLUE);
        style.getCharacterFormat().setFontName("Arial");
        style.getCharacterFormat().setFontSize(18f);
        doc.getStyles().add(style);
        paragraph1.applyStyle("titleStyle");

        //Set horizontal alignment for paragraph 1 and paragraph 2
        paragraph1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        paragraph2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        
        //Set space after paragraph 1
        paragraph1.getFormat().setAfterSpacing(15f);
        
        //Save the Document object
        doc.saveToFile("InsertImage.docx", FileFormat.Docx_2013);
    }
}

Output:

Insert Image into Word Document in Java

The following code snippets demonstrate how to use Spire.Doc for Java to set the background for word document in Java programs, including how to set background image, background solid color and background gradient color.

Java set background image for word document:

import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import java.awt.*;
import java.io.*;

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

        String inputFile="Sample.docx";
        String backgroundImg="background.png";
        String outputFile="out/result.docx";

        //load a word document
        Document document= new Document(inputFile);

        //set the background type as picture
        document.getBackground().setType(BackgroundType.Picture);

        //set the background picture
        document.getBackground().setPicture(backgroundImg);

        //save the file
        document.saveToFile(outputFile, FileFormat.Docx);
    }
}

Java set background image and background color for word document

Java set background solid color for word document:

import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import java.awt.*;
import java.io.*;

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

        String inputFile="Sample.docx";
        String outputFile="out/result2.docx";

        //load a word document
        Document document= new Document(inputFile);

        document.getBackground().setType(BackgroundType.Color);
        document.getBackground().setColor(Color.lightGray);

        //save the file
        document.saveToFile(outputFile, FileFormat.Docx);
    }
}

Java set background image and background color for word document

Java set background gradient color for word document:

import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import com.spire.doc.documents.GradientShadingStyle;
import com.spire.doc.documents.GradientShadingVariant;
import java.awt.*;
import java.io.*;

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

        String inputFile="Sample.docx";
        String outputFile="out/result3.docx";

        //load a word document
        Document document= new Document(inputFile);

        document.getBackground().setType(BackgroundType.Gradient);
        document.getBackground().getGradient().setColor1(Color.white);
        document.getBackground().getGradient().setColor2(Color.green);
        document.getBackground().getGradient().setShadingVariant(GradientShadingVariant.Shading_Down);
        document.getBackground().getGradient().setShadingStyle(GradientShadingStyle.Horizontal);

        //save the file
        document.saveToFile(outputFile, FileFormat.Docx_2013);
    }
}

Java set background image and background color for word document

Wednesday, 01 May 2019 01:56

Encrypt and Decrypt Word Document in Java

This article demonstrates how to encrypt a Word document with a password as well as remove the encryption by using Spire.Doc for Java.

Encrypt Document

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class EncryptWord {

    public static void main(String[] args) {

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

        //load a Word document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //encrypt the document with a password
        document.encrypt("abc-123");

        //save as docx file
        document.saveToFile("output/Encrypt.docx", FileFormat.Docx);
    }
}

Decrypt Document

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class DecryptWord {

    public static void main(String[] args) {

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

        //remove encryption while loading the password protected document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encrypt.docx", FileFormat.Docx, "abc-123");

        //save as docx file.
        document.saveToFile("output/Decrypt2.docx", FileFormat.Docx);
    }
}
Page 8 of 113