Spire.Doc for Java supports adding the following two types of document properties to Word document:

  • Built-in document properties
  • Custom document properties

In this article, we will see how to use Spire.Doc for Java to add the above document properties into a Word document.

Add Built-In Document Properties

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

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

        //Add built-in document properties to the Word document
        document.getBuiltinDocumentProperties().setTitle("Document Demo Document");
        document.getBuiltinDocumentProperties().setSubject("demo");
        document.getBuiltinDocumentProperties().setAuthor("James");
        document.getBuiltinDocumentProperties().setCompany("e-iceblue");
        document.getBuiltinDocumentProperties().setManager("Jakson");
        document.getBuiltinDocumentProperties().setCategory("Doc Demos");
        document.getBuiltinDocumentProperties().setKeywords("Document, Property, Demo");
        document.getBuiltinDocumentProperties().setComments("This document is just a demo.");

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

Add Document Properties to Word Document in Java

Add Custom Document Properties

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

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

        //Load Word document
        Document document = new Document("Input.docx");

        //Add custom document properties to the Word document
        document.getCustomDocumentProperties().add("TrackingID", "AB01");
        document.getCustomDocumentProperties().add("Checked By", "Wilson");

        //Save the resultant document
        document.saveToFile("SetCustomProperties.docx", FileFormat.Docx_2013);

    }
}

Add Document Properties to Word Document in Java

Wednesday, 29 May 2019 07:35

Add Digital Signature to Word in C#

This article demonstrates how to add digital signature to a Word document using Spire.Doc.

Spire.Doc provides us the following methods to add digital signature to Word document:

  • public void SaveToFile(string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
  • public void SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword);
  • public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] certificateData, string securePassword);
  • public void SaveToStream(Stream stream, FileFormat fileFormat, string certificatePath, string securePassword);
  • public static byte[] Sign(Stream sourceStream, byte[] certificateData, string securePassword);
  • public static byte[] Sign(Stream sourceStream, string certificatePath, string securePassword);

In the following example, we'll see how to add digital signature to a Word document and save the result to file using the SaveToFile method with Document object.

//Load the Word document
Document doc = new Document("sample.docx");
//Sign the document with certificate and save to file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, "gary.pfx", "e-iceblue");

We can also add digital signature to a Word document and save the result to stream using the SaveToStream method with Document object.

//Load the Word document
Document doc = new Document("sample.docx");
//Create a FileStream
FileStream fs = new FileStream();
//Sign the document with certificate and save to stream
doc.SaveToStream(fs, FileFormat.Docx2013, "gary.pfx", "e-iceblue");
fs.Flush();

The following example shows how to add digital signature to a Word document using the Sign method with Document class.

//Read the Word document into a FileStream
FileStream fs = File.OpenRead("sample.docx");
//Sign the document using Sign method with Document class
byte[] result = Document.Sign(fs, "gary.pfx", "e-iceblue");
File.WriteAllBytes("AddDigitalSignature.docx", result);
fs.Flush();

The output document:

Add Digital Signature to Word in C#

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

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

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

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

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

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

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

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

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

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

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

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

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

This article demonstrates how to add text, images, lines and page numbers to the header or footer of a Word document by using Spire.Doc for Java.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

public class InsertHeaderAndFooter {

    public static void main(String[] args) {

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

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

        //call insertHeaderAndFooter method to add header and footer to the section
        insertHeaderAndFooter(section);

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

    private static void insertHeaderAndFooter(Section section) {

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

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

        //insert a picture to header paragraph and set its position
        DocPicture headerPicture = headerParagraph.appendPicture("C:\\Users\\Administrator\\Desktop\\Logo.png");
        headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left);
        headerPicture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
        headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Bottom);

        //add text to header paragraph
        TextRange text = headerParagraph.appendText("Demo of Spire.Doc");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(10);
        text.getCharacterFormat().setItalic(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

        //set text wrapping to behind
        headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind);

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

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

        //add Field_Page and Field_Num_Pages fields to the footer paragraph
        footerParagraph.appendField("page number", FieldType.Field_Page);
        footerParagraph.appendText(" of ");
        footerParagraph.appendField("number of pages", FieldType.Field_Num_Pages);
        footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

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

Insert Header and Footer to Word in Java

Friday, 24 May 2019 09:25

Create Table in Word in Java

This article demonstrates how to create table in a Word document using Spire.Doc for Java.

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

import java.awt.*;

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

        //Data used to create table
        String[] header = {"Name", "Capital", "Continent", "Area", "Population"};
        String[][] data =
                {
                        new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"},
                        new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
                        new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
                        new String[]{"Canada", "Ottawa", "North America", "9976147", "26500000"},
                        new String[]{"Chile", "Santiago", "South America", "756943", "13200000"},
                        new String[]{"Colombia", "Bogota", "South America", "1138907", "33000000"},
                        new String[]{"Cuba", "Havana", "North America", "114524", "10600000"},
                        new String[]{"Ecuador", "Quito", "South America", "455502", "10600000"},
                        new String[]{"El Salvador", "San Salvador", "North America", "20865", "5300000"},
                        new String[]{"Guyana", "Georgetown", "South America", "214969", "800000"},
                        new String[]{"Jamaica", "Kingston", "North America", "11424", "2500000"},
                        new String[]{"Mexico", "Mexico City", "North America", "1967180", "88600000"},
                        new String[]{"Nicaragua", "Managua", "North America", "139000", "3900000"},
                        new String[]{"Paraguay", "Asuncion", "South America", "406576", "4660000"},
                        new String[]{"Peru", "Lima", "South America", "1285215", "21600000"},
                        new String[]{"America", "Washington", "North America", "9363130", "249200000"},
                        new String[]{"Uruguay", "Montevideo", "South America", "176140", "3002000"},
                        new String[]{"Venezuela", "Caracas", "South America", "912047", "19700000"}
                };

        //Add table
        Table table = section.addTable(true);
        table.resetCells(data.length + 1, header.length);

        //Set the first row as table header and add data
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(20);
        row.setHeightType(TableRowHeightType.Exactly);
        row.getRowFormat().setBackColor(Color.gray);
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange txtRange = p.appendText(header[i]);
            txtRange.getCharacterFormat().setBold(true);
        }

        //Add data to the rest of rows
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            dataRow.getRowFormat().setBackColor(Color.white);
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
            }
        }

        //Set background color for cells
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 0; f < row2.getCells().getCount(); f++) {
                    row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
                }
            }
        }

        //save the document
        document.saveToFile("CreateTable.docx", FileFormat.Docx_2013);
    }
}

Output:

Create Table in Word in Java

This article demonstrates how to add and delete bookmarks in an existing Word document using Spire.Doc for Java.

Insert Bookmark

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

public class InsertBookmark {

    public static void main(String[] args) {

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

        //load an existing Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //get the the paragraph where you want to insert bookmark
        Paragraph paragraph = doc.getSections().get(0).getParagraphs().get(1);

        //append a bookmark start and remove it to the beginning of the paragraph
        BookmarkStart start = paragraph.appendBookmarkStart("myBookmark");
        paragraph.getItems().insert(0,start);
        
        //append a bookmark end at the end of the paragraph
        paragraph.appendBookmarkEnd("myBookmark");
        
        //save the file
        doc.saveToFile("output/AddBookmark.docx", FileFormat.Docx_2013);
    }
}

Insert and Remove Bookmarks in Word in Java

Remove Bookmark

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

public class RemoveBookmark {

    public static void main(String[] args) {

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

        //load an existing Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\AddBookmark.docx");
        
        //get bookmark by its index
        Bookmark bookmark = doc.getBookmarks().get(0);

        //remove the bookmark
        doc.getBookmarks().remove(bookmark);

        //save the document.
        doc.saveToFile("output/RemoveBookmark.docx", FileFormat.Docx);
    }
}

Insert and Remove Bookmarks in Word in Java

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