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);
    }
}
Friday, 26 April 2019 08:26

Create Word Document in Java

This article demonstrates how to create Word document, add paragraphs and set paragraph styles in Java using Spire.Doc for Java.

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

import java.awt.*;

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

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

       //Add 3 paragraphs to the section
        Paragraph para1 = section.addParagraph();
        para1.appendText("Spire.Doc for Java");

        Paragraph para2 = section.addParagraph();
        para2.appendText("Spire.Doc for Java is a professional Java Word API that enables Java applications " +
                "to create, convert, manipulate and print Word documents without using Microsoft Office.");

        Paragraph para3 = section.addParagraph();
        para3.appendText("A plenty of Word document processing tasks can be performed by Spire.Doc for Java, " +
                "such as create, read, edit, convert and print Word documents, insert image, add header and footer, " +
                "create table, add form field and mail merge field, add bookmark and watermark, add hyperlink, " +
                "set background color/image, add footnote and endnote, encrypt Word documents.");

        //Set title style for paragraph 1
        ParagraphStyle style1 = new ParagraphStyle(document);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);
        style1.getCharacterFormat().setTextColor(Color.BLUE);
        style1.getCharacterFormat().setFontName("Arial");
        style1.getCharacterFormat().setFontSize(12f);
        document.getStyles().add(style1);
        para1.applyStyle("titleStyle");

        //Set style for paragraph 2 and 3
        ParagraphStyle style2 = new ParagraphStyle(document);
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Arial");
        style2.getCharacterFormat().setFontSize(11f);
        document.getStyles().add(style2);
        para2.applyStyle("paraStyle");
        para3.applyStyle("paraStyle");

        //Horizontally align paragraph 1 to center
        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set first-line indent for paragraph 2 and 3
        para2.getFormat().setFirstLineIndent(25f);
        para3.getFormat().setFirstLineIndent(25f);

        //Set spaces after paragraph 1 and 2
        para1.getFormat().setAfterSpacing(15f);
        para2.getFormat().setAfterSpacing(10f);

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

Output:

Create Word Document in Java

When you create a Word document with Spire. Doc for Java, you can format an entire paragraph by applying a ParagraphStyle, you can also format individual words or phrases by applying a CharacterFormat. This article introduces how to apply formatting to characters in Word.

Code Snippets

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.TextRange;

import java.awt.*;

public class SetCharacterFormat {

    public static void main(String[] args) {

        //create a Word document
        Document document = new Document();
        Section sec = document.addSection();

        //add a paragraph
        Paragraph paragraph = sec.addParagraph();
        paragraph.appendText("Here is a paragraph with various character styles. This is ");

        //append text to the paragraph and return a TextRange object
        TextRange tr = paragraph.appendText("text with strikeout");

        //set the character format to strikeout via TextRange object
        tr.getCharacterFormat().isStrikeout(true);

        //apply shadow effect to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with shadow");
        tr.getCharacterFormat().isShadow(true);

        //apply a large font size to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in a large font size");
        tr.getCharacterFormat().setFontSize(20);

        //apply color to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in red");
        tr.getCharacterFormat().setTextColor(Color.red);

        //apply bold & italic to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in bold & italic");
        tr.getCharacterFormat().setBold(true);
        tr.getCharacterFormat().setItalic(true);

        //apply underline to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("underlined text");
        tr.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);

        //apply background color to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with background color");
        tr.getCharacterFormat().setTextBackgroundColor(Color.GREEN);

        //apply superscript to text
        paragraph.appendText(". This is a math formula: a");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(" + b");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(" = c");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(".");

        //save to file
        document.saveToFile("SetCharacterFormat.docx", FileFormat.Docx);
    }
}

Output

Apply Formatting to Characters in Word in Java

This section will demonstrate how to use Spire.Doc for Java to add text watermark and image watermark to Word document in Java applications.

Add text watermark

import com.spire.doc.*;
import com.spire.doc.documents.WatermarkLayout;
import java.awt.*;

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

        Document document = new Document();
        document.loadFromFile("Sample.docx");

        insertTextWatermark(document.getSections().get(0));

        document.saveToFile("out/result.docx",FileFormat.Docx );
    }
    private static void insertTextWatermark(Section section) {
        TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText("Confidential");
        txtWatermark.setFontSize(40);
        txtWatermark.setColor(Color.red);
        txtWatermark.setLayout(WatermarkLayout.Diagonal);
        section.getDocument().setWatermark(txtWatermark);
    }

}

Effective screenshot of text watermark on word:

Java add text watermark and image watermark to word document

Add image watermark

import com.spire.doc.*;


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

        Document document = new Document();
        document.loadFromFile("Sample.docx");

         PictureWatermark picture = new PictureWatermark();
         picture.setPicture("logo.png");
         picture.setScaling(5);
         picture.isWashout(false);
         document.setWatermark(picture);

         document.saveToFile("out/result2.docx",FileFormat.Docx );
    }
}

Effective screenshot of image watermark on word:

Java add text watermark and image watermark to word document

With the help of Spire.Presentation, developers can easily add and get speaker notes on presentation slides. From v 4.4.3, Spire.Presentation supports to retain the notes when converting presentation slides to SVG. This article will show you how to keep the notes when saving presentation slides to SVG in C#.

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.IO;
using System.Collections.Generic;

namespace PPT
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the sample document with speaker notes
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            //retain the notes when converting ppt to svg
            ppt.IsNoteRetained = true;


            //convert presentation slides to SVG
            Queue<byte[]> bytes = ppt.SaveToSVG();

            int length = bytes.Count;
            for (int i = 0; i < length; i++)
            {
                FileStream filestream = new FileStream(string.Format(@"output_{0}.svg", i), FileMode.Create);
                byte[] outputBytes = bytes.Dequeue();
                filestream.Write(outputBytes, 0, outputBytes.Length);
            }
            ppt.Dispose();
            ppt.SaveToSVG();
                                                       
        }
    }
}

Effective screenshot of retaining the speaker notes when converting presentation slides to SVG:

C# retain notes when converting presentation slides to SVG