Java: Set Paragraph Indents in Word
In Microsoft Word, we can set the paragraph indents as left, right, first line or hanging. In this article, we will demonstrate how to achieve this functionality 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>
Set Paragraph Indents in Word
Spire.Doc for Java provides a ParagraphFormat class to work with paragraph formatting. You can use Paragraph.getFormat() method to get the ParagraphFormat object, and then use the following methods to set the corresponding paragraph indents with the object:
Indents | Methods | Descriptions |
Left | ParagraphFormat.setLeftIndent(float value) | Indents the paragraph on the left by the amount you set. |
Right | ParagraphFormat.setRightIndent(float value) | Indents the paragraph on the right by the amount you set. |
First line | ParagraphFormat.setFirstLineIndent(float value) | Indent the first line of a paragraph. |
Hanging | ParagraphFormat.setFirstLineIndent(float negativeValue) | Sets off the first line of a paragraph by positioning it at the margin, and then indenting each subsequent line of the paragraph. |
The following are the steps to set paragraph indents:
- Create a Document instance.
- Load a Word document using Document.loadFromFile() method.
- Get the desired section by its index using Document.getSections.get() method.
- Get the desired paragraph by index using Section.getParagraphs.get() method.
- Get the ParagraphFormat object using Paragraph.getFormat() method.
- Call the methods listed in above table to set paragraph indents with the object.
- Save the result document 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.Paragraph; import com.spire.doc.formatting.ParagraphFormat; public class IndentParagraph { public static void main(String[] args) { //Create a Document instance Document document= new Document(); //Load a Word document document.loadFromFile("Input.docx"); //Get the first section Section section = document.getSections().get(0); //Get the second paragraph and set left indent Paragraph para = section.getParagraphs().get(1); ParagraphFormat format = para.getFormat(); format.setLeftIndent(30); //Get the third paragraph and set right indent para = section.getParagraphs().get(2); format = para.getFormat(); format.setRightIndent(30); //Get the fourth paragraph and set first line indent para = section.getParagraphs().get(3); format = para.getFormat(); format.setFirstLineIndent(30); //Get the fifth paragraph and set hanging indent para = section.getParagraphs().get(4); format = para.getFormat(); format.setFirstLineIndent(-30); //Save the result document document.saveToFile("SetParagraphIndents.docx", FileFormat.Docx_2013); } }
The following is the output Word document after setting paragraph indents:
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: Add, Delete or Reply to Comments in Word
MS Word Comments feature allows authors to discuss the content with the readers without having to directly edit the content. It is a good way to keep the document neat and clean. In this article, you will learn how to add, delete, or reply to comments in a Word document using Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project’s pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.4.6</version> </dependency> </dependencies>
Add a Comment to Word
Spire.Doc offers the Paragraph.appendComment() method to a paragraph. The detailed steps are as follows.
- Load the sample Word document while initializing the Document object.
- Get the specific section using Document.getSection() method.
- Get the paragraphs collection using Section.getParagraphs() method, and then get the specific paragraph using ParagraphCollection.get() method.
- Add a comment to the paragraph using Paragraph.appendComment() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.fields.Comment; public class AddComment { public static void main(String[] args) { //Load the sample Word document Document document= new Document("C:\\Users\\Administrator\\Desktop\\Sample.docx"); //Get the first section Section section = document.getSections().get(0); //Get the second paragraph Paragraph paragraph = section.getParagraphs().get(1); //Add a comment Comment comment = paragraph.appendComment("Spire.Doc for Java"); comment.getFormat().setAuthor("E-iceblue"); comment.getFormat().setInitial("CM"); //Save to file document.saveToFile("output/AddComment.docx", FileFormat.Docx); } }
Reply to a Comment
To add a reply to an existing comment, use Comment.replyToComment() method. The following are the detailed steps.
- Load the sample Word document while initializing the Document object.
- Get the comment collection using Document.getComments() method, and then get the specific comment using CommentsCollection.get() method.
- Create a new instance of Comment class, and specify its content and author.
- Add the comment as a reply to an existing comment using Comment.replyToComment() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.FileFormat; import com.spire.doc.fields.*; public class ReplyToComment { public static void main(String[] args) { //Load the sample Word document Document document= new Document("C:\\Users\\Administrator\\Desktop\\Sample.docx"); //Get the first comment Comment comment1 = document.getComments().get(0); //Initialize a Comment object Comment replyComment = new Comment(document); //Set the author and content of the comment replyComment.getFormat().setAuthor("E-iceblue"); replyComment.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 first comment comment1.replyToComment(replyComment); //Save to file document.saveToFile("output/ReplyToComment.docx", FileFormat.Docx); }
Delete a Comment from Word
After getting the comments collection through Document.getComments() method, you can use CommentsCollection.removeAt() method to delete the specific comment by its index. Here come the detailed steps.
- Load the sample Word document while initializing the Document object.
- Get the comments collection using Document.getComments() method.
- Remove the specific comment using CommentsCollection.removeAt() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.FileFormat; public class DeleteComment { public static void main(String[] args) { //Load the sample Word document Document document= new Document("C:\\Users\\Administrator\\Desktop\\Sample.docx"); //Remove the comment by its index document.getComments().removeAt(1); //Save to file document.saveToFile("output/DeleteComment.docx", FileFormat.Docx); } }
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.
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 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); } }
Java: Find and Replace Text in Word Documents
There are always troublesome situations in the process of creating Word documents. For example, after completing a large Word document, it is discovered that someone’s name or a term, which appears multiple times in the document, was misspelled. Fortunately, there are some simple ways to solve such problems. MS Word has a find-and-replace feature to help users to find the misspelled words in a Word document and replace them with the right ones. However, if you don’t have MS Word, or if you want your application to implement this feature, Spire.Doc for Java is also a good choice. This article shows how to use the professional development component Spire.Doc for Java to find and replace text with new text or images in a Word document.
- Find Text and Replace All Matches with New Text
- Find Text and Replace the First Match with New Text
- Find and Replace Text with a Picture
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>
Find Text and Replace All Matches with New Text
Finding and replacing text in Word documents can be done by Spire.Doc for Java with a simple method Document.replace(). This method replaces all matches of the searched text with new text, and you can decide whether to consider the case and whether to search for whole words.
The detailed steps of finding text and replacing all matches are as follows:
- Create a Document class instance.
- Load a Word document using Document.loadFromFile() method.
- Replace all the matches of text "deer" in the document with new text "buffalo" using Document.replace() method.
- Save the result document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; public class replaceText { public static void main(String[] args) { //Create a Document class instance Document document = new Document(); //Load a Word document document.loadFromFile("Cave Art.docx"); //Replace all the matches of text “deer” in the document with new text “buffalo” document.replace("deer", "buffalo", false, true); //Save the result document document.saveToFile("Find&Replace.docx"); } }
Find Text and Replace the First Match with New Text
Spire.Doc for Java also provides the Document.setReplaceFirst() method to change the replacement mode of the Document.replace() method to replace the first match or replace all matches.
The detailed steps of finding text and replacing the first match are as follows:
- Create a Document class instance.
- Load a Word document using Document.loadFromFile() method.
- Change the replacement mode as replacing only the first match using Document.setReplaceFirst() method.
- Replace the first match of text "deer" in the document with new text "buffalo" using Document.replace() method.
- Save the result document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; public class replaceText { public static void main(String[] args) { //Create a Document class instance Document document = new Document(); //Load a Word document document.loadFromFile("Cave Art.docx"); //Set the replacement mode as replacing only the first match document.setReplaceFirst(true); //Replace all the matches of text “deer” in the document with new text “buffalo” document.replace("deer", "buffalo", false, true); //Save the result document document.saveToFile("Find&Replace.docx"); } }
Find and Replace Text with a Picture
Spire.Doc for Java supports searching text and replacing all matches as pictures as well. To do so, you need to search for the text and get all matches. Then load a picture as a document object, insert it to where the matching text is, and delete the text.
The detailed steps of finding and replacing text with images are as follows:
- Create a Document class instance.
- Load a Word document using Document.loadFromFile() method.
- Find all the strings matching 'deer' in the document using Document.findString() method.
- Loop through the matches to replace all of them with the picture.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.documents.TextSelection; import com.spire.doc.fields.DocPicture; import com.spire.doc.fields.TextRange; public class replaceTextWithImage { public static void main(String[] args) { //Create a Document class instance Document document = new Document(); //Load a Word document document.loadFromFile("Cave Art.docx"); //Find all the strings matching 'deer' in the document TextSelection[] selections = document.findAllString("deer", true, true); //Replace all the matches with the image int index = 0; TextRange range = null; for (Object obj : selections) { TextSelection textSelection = (TextSelection)obj; //Create an object of DocPicture class and load a picture DocPicture pic = new DocPicture(document); pic.loadImage("deer.png"); range = textSelection.getAsOneRange(); index = range.getOwnerParagraph().getChildObjects().indexOf(range); range.getOwnerParagraph().getChildObjects().insert(index,pic); range.getOwnerParagraph().getChildObjects().remove(range); } //Replace a specific match with the picture //Create an object of DocPicture class and load a picture //DocPicture pic = new DocPicture(document); //pic.loadImage("deer.png"); //Object object = selections[1]; //TextSelection selection = (TextSelection) object; //TextRange textRange = selection.getAsOneRange(); //int i = textRange.getOwnerParagraph().getChildObjects().indexOf(textRange); //textRange.getOwnerParagraph().getChildObjects().insert(i,pic); //textRange.getOwnerParagraph().getChildObjects().remove(textRange); //Save the document document.saveToFile("ReplaceTextWithImage.docx", FileFormat.Docx_2013); } }
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: Find and Highlight Text in Word
The "Find" function in MS Word allows users to search for specific text or phrases in a document quickly, and users can also highlight the found text in yellow or other bright colors to make them visible to readers at a glance. In this article, you will learn how to programmatically find and highlight text in a Word document using Spire.Doc for Java.
Install Spire.Doc for Java
First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.4.6</version> </dependency> </dependencies>
Find and Highlight Text in Word
The detailed steps are as follows.
- Create a Document instance
- Load a sample Word document using Document.loadFromFile() method.
- Find all matching text in the document using Document.findAllString(java.lang.String matchString, boolean caseSensitive, boolean wholeWord) method.
- Loop through all matching text in the document.
- Get the text range of a specific matching text using TextSelection.getAsOneRange() method, and then set its highlight color using TextRange.getCharacterFormat().setHighlightColor() method.
- Save the result document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.TextSelection; import java.awt.*; public class FindAndHighlight { public static void main(String[] args){ //Create a Document instance Document document = new Document(); //Load a sample Word document document.loadFromFile("E:\\Files\\input1.docx"); //Find all matching text in the document TextSelection[] textSelections = document.findAllString("transcendentalism", false, true); //Loop through all matching text and set highlight color for them for (TextSelection selection : textSelections) { selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW); } //Save the document document.saveToFile("FindAndHighlight.docx", FileFormat.Docx_2013); } }
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 and Images from Word
Text and images are crucial elements that can enrich the content of a Word document. When users need to manipulate text or images separately of the document, programmatically extracting them from a Word document provides an optimal solution. Extracting text guarantees greater convenience and efficiency when dealing with large documents compared to manually copying text. Additionally, image extraction enables users to perform further editing on the images of the document or effortlessly share them with others. In this article, we will demonstrate how to extract text and images from Word in Java by 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>
Extract Text from Word in Java
Spire.Doc for Java supports extracting text from Word documents and saving it as a text file format, which allows users to view text content without device restrictions. Below are detailed steps for extracting text from a Word document.
- Create a Document object.
- Load a word document using Document.loadFromFile method.
- Get text from document as string using Document.getText() method.
- Call writeStringToTxt() method to write string to a specified text file.
- Java
import com.spire.doc.Document; import java.io.FileWriter; import java.io.IOException; public class ExtractText { public static void main(String[] args) throws IOException { //Create a Document object and load a Word document Document document = new Document(); document.loadFromFile("sample1.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 Images from Word in Java
By extracting images, users are able to import image data into other applications for further processing without difficulty. Spire.Doc for Java allows users to extract images from Word documents and save them to the specified path. The following are detailed steps.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Create a queue of composite objects.
- Add the root document element to the traversal queue using Queue<ICompositeObject>.add(ICompositeObject e) method.
- Create a ArrayList object to store extracted images.
- Traverse the document tree and check for composite or picture objects by iterating over the children node of each node.
- Check if the child element is a composite object. If so, add it to the queue for further processing.
- Check if the child element is a picture object. If so, extract its image data and add it to the extracted image list.
- Save images to the specific folder using ImageIO.write(RenderedImage im, String formatName, File output) method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.*; import com.spire.doc.interfaces.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; public class ExtractImage { public static void main(String[] args) throws IOException { //Create a Document object and load a Word document Document document = new Document(); document.loadFromFile("sample2.docx"); //Create a queue and add the root document element to it Queue<ICompositeObject> nodes = new LinkedList<>(); nodes.add(document); //Create a ArrayList object to store extracted images List<BufferedImage> images = new ArrayList<>(); //Traverse the document tree 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); } else if (child.getDocumentObjectType() == DocumentObjectType.Picture) { DocPicture picture = (DocPicture) child; images.add(picture.getImage()); } } } //Save images to the specific folder for (int i = 0; i < images.size(); i++) { File file = new File(String.format("output/extractImage-%d.png", i)); ImageIO.write(images.get(i), "PNG", file); } } }
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 Page Margins for Word Documents
Page margins are the blank spaces between the body content and the page edges. In Microsoft Word, the default margins of each page are set as 1 inch, but sometimes you may need to resize the margins to accordance with your requirements. In this article, you will learn how to set page margins for Word documents in Java 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>
Set Page Margins in Word in Java
The following are the steps to set page margins in a Word document:
- Initialize an instance of Document class.
- Load a Word document using Document.loadFromFile() method.
- Get the desired section through Document.getSections().get(sectionIndex) method.
- Set the top, bottom, left and right margins for the pages in the section through Section.getPageSetup().getMargins().setTop(), Section. getPageSetup().getMargins().setBottom(), Section. getPageSetup().getMargins().setLeft(), Section.getPageSetup().getMargins().setRight() methods.
- Save the result document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.Section; public class SetPageMargins { public static void main(String []args){ //Create a Document instance Document document = new Document(); //Load a Word document document.loadFromFile("Sample.docx"); //Get the first section Section section = document.getSections().get(0); //Set top, bottom, left and right page margins for the section section.getPageSetup().getMargins().setTop(17.9f); section.getPageSetup().getMargins().setBottom(17.9f); section.getPageSetup().getMargins().setLeft(17.9f); section.getPageSetup().getMargins().setRight(17.9f); //Save the result document document.saveToFile("SetMargins.docx", FileFormat.Docx_2013); } }
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: Insert Images to Word Documents
MS Word allows users to insert a lot of elements in Word documents, including text, images, charts, and files. Images are frequently used in Word documents to make them intuitive, to express ideas that are hard to express in words, or just to make them beautiful. This article provides you a convenient and efficient way to insert images to Word documents under the help of Spire.Doc for Java.
- Insert an Image to a Word Document with Specified Text Wrapping Style
- Insert an Image to a Word Document at a Specific Location
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 an Image to a Word Document with Specified Text Wrapping Style
The detailed steps of inserting images with specified wrapping style are as follows:
- Create an object of Document class.
- Load a Word document from disk using Document.loadFromFile() method.
- Create an object of DocPicture class.
- Load an image from disk using DocPicture.loadImage() method.
- Set the size of the image using DocPicture.setWidth() and DocPicture.setHeight() method.
- Set the text wrapping style of the image as Square using DocPicture.setTextWrappingStyle() method.
- Insert the image at the start of the second paragraph using Paragraph.getChildObjects().insert() method.
- Save the document using Document.saveToFile method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.*; public class insertImage { public static void main(String[] args) throws Exception { //Create an object of Document class Document doc = new Document(); //Load a Word document from disk doc.loadFromFile("D:/Samples/Sample.docx"); //Create an object of DocPicture class DocPicture picture = new DocPicture(doc); //Load an image from disk picture.loadImage("D:/Samples/System.png"); //Set the size of the image picture.setWidth(75); picture.setHeight(90); //Set the text wrapping style of the image as Square picture.setTextWrappingStyle( TextWrappingStyle.Square); //Insert the image at the start of the second paragraph doc.getSections().get(0).getParagraphs().get(1).getChildObjects().insert(0,picture); //Save the document doc.saveToFile("D:/javaOutput/insertImage.docx", FileFormat.Docx); } }
Insert an Image to a Word Document at a Specific Location
The detailed steps of inserting images at a specific location are as follows:
- Create an object of Document class.
- Load a Word document from disk using Document.loadFromFile() method.
- Create an object of DocPicture class.
- Load an image from disk using DocPicture.loadImage() method.
- Set the size of the image using DocPicture.setWidth() and DocPicture.setHeight() method.
- Set the text wrapping style of the image as Tight using DocPicture.setTextWrappingStyle() method.
- Insert the image into the third paragraph using Paragraph.getChildObjects().insert() method.
- Set the position of the image using DocPicture.setHorizontalPosition() and DocPicture.setVerticalPositon() method. The original location is at the start of the selected paragraph.
- Save the document using Document.saveToFile method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.*; public class insertImage { public static void main(String[] args) throws Exception { //Create an object of Document class Document doc = new Document(); //Load a Word document from disk doc.loadFromFile("D:/Samples/Sample.docx"); //Create an object of DocPicture class DocPicture picture = new DocPicture(doc); //Load an image from disk picture.loadImage("D:/Samples/PDF.png"); //Set the size of the image picture.setWidth(75); picture.setHeight(90); //Set the text wrapping style of the image as Tight picture.setTextWrappingStyle( TextWrappingStyle.Tight); //Insert the image into the Third paragraph doc.getSections().get(0).getParagraphs().get(2).getChildObjects().insert(0,picture); //Set the position of the image picture.setHorizontalPosition(370.0F); picture.setVerticalPosition(10.0F); //Save the document doc.saveToFile("D:/javaOutput/insertImage.docx", FileFormat.Docx); } }
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: Add Background Color or Picture to Word Documents
The background of a Word document is blank by default. For documents like brochures, invitations, handouts, and marketing materials, blank backgrounds will be too tedious. A good-looking background can be a great attraction to readers. Therefore, you can add a color or insert an image as a background to make your documents more appealing. This article shows how to set background color or image for Word documents by programming using Spire.Doc for Java.
- Add a Background Color to a Word Document
- Add a Gradient Background to a Word Document
- Insert a Background Image to a Word Document
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 Background Color to a Word Document
Adding a background color to a Word document is very easy. You only need to set the background type as color and then choose a color as your background. The detailed steps are as follows.
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Set the background type as color using Document.getBackground().setType() method.
- Set the background color using Document.getBackground().setColor() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import java.awt.*; import java.io.*; public class addBackgroundColor { public static void main(String[] args) throws IOException { //Create an object of Document class Document document= new Document(); //Load a Word document document.loadFromFile("C:/Sample.docx"); //Set the background type as color document.getBackground().setType(BackgroundType.Color); //Set the background color as orange document.getBackground().setColor(Color.orange); //Save the document document.saveToFile("AddBackgroundColor.docx", FileFormat.Docx); } }
Add a Gradient Background to a Word Document
Adding gradient background requires more steps. You need to set the background type as gradient, choose two colors, and then set shading variant and style. The detailed steps are as follows.
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Set the background type as gradient using Document.getBackground().setType() method.
- Choose two colors using >Background.getGradient().setColor1() and Background.getGradient().setColor2() method.
- Set shading variant using Background.getGradient().setShadingVariant() method.
- Set shading style using Background.getGradient().setShadingStyle() method.
- Save the document using Document.saveToFile() method.
- Java
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 addBackgroundColor { public static void main(String[] args) throws IOException { //load a word document Document document= new Document("C:/Sample.docx"); //Set the background type as gradient document.getBackground().setType(BackgroundType.Gradient); //Choose two colors Background background = document.getBackground(); background.getGradient().setColor1(Color.white); background.getGradient().setColor2(Color.orange); //Choose gradient variant background.getGradient().setShadingVariant(GradientShadingVariant.Shading_Down); //Choose gradient style background.getGradient().setShadingStyle(GradientShadingStyle.Horizontal); //Save the document document.saveToFile("AddGradientBackground.docx", FileFormat.Docx_2013); } }
Insert Background Image to a Word Document
To insert a background picture to a Word document, you need to set the background type as picture, and then insert a picture as the background. The detailed steps are as follows.
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Change the background type to picture using Document.getBackground().setType() method.
- Insert a picture as the background using Document.getBackground().setPicture() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import java.io.*; public class addBackgroundColor { public static void main(String[] args) throws IOException { //Create an object of Document class Document document= new Document(); //Load a Word document document.loadFromFile("C:/Sample.docx"); //Set the background type as picture document.getBackground().setType(BackgroundType.Picture); //Set the background picture document.getBackground().setPicture("C:/background.jpg"); //Save the document document.saveToFile("AddBackgroundPicture.docx", FileFormat.Docx); } }
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: Protect or Unprotect Word Documents
Enabling security options of your Word documents is essential for keeping sensitive information safe. You can encrypt your document with a password so that it cannot be opened by unauthorized users; you can enable the Read-only mode to prevent users from changing the content; you can also partially restrict editing your document. This article demonstrates how to protect or unprotect Word documents in Java using Spire.Doc for Java.
- Protect a Word Document with a Password in Java
- Change Permission of a Word Document in Java
- Lock Specified Sections of a Word Document in Java
- Mark a Word Document as Final in Java
- Remove Password from an Encrypted Word Document in 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>
Protect a Word Document with a Password in Java
Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to password protect a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Encrypt the document with a password using Document.encrypt() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Change Permission of a Word Document in Java
Documents encrypted with an open password cannot be opened by those who do not know the password. If you’d like to grant people permission to read your document but restrict the types of modifications that someone can make, you can set the document permission. The following are the steps to change permission of a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Set the document permission and the permission password using Document.protect() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { 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"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Lock Specified Sections of a Word Document in Java
You can lock parts of your Word document so that they cannot be changed and leave the unlocked parts available for editing. The following are the steps to protect specified sections of a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Set the editing restriction as Allow_Only_Form_Fields.
- Unprotect a specific section by passing false to Section.protectForm() as a parameter. The rest sections will continue to be protected.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Mark a Word Document as Final in Java
By marking a document as Final, you disable typing, editing, and format changes capabilities and a message will appear to any reader that the document has been finalized. The following are the steps to mark a Word document as final using Spire.Doc for Java.
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Get the CustomDocumentProperties object from the document.
- Add a custom property "_MarkAsFinal" to the document.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Remove Password from an Encrypted Word Document in Java
You can remove the password from an encrypted document if the encryption is no longer needed. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Remove the password using Document.removeEncryption() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
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.