· 

Java - Embed an External File in a Word Document

To make your point of view more reasonable and convincible, you can attach/embed an external document containing statistical information or any other relevant material in your Word document. In this article, I am going to show you how to embed a Word document to another as an OLE object by using Free Spire.Doc for Java. If you want, you can also embed PDF, Excel, PowerPoint document, image file or video clip to your document.

Installing Spire.Doc.jar

If you create a Maven project, you can easily import the jar in your application using the following configurations. For non-Maven projects, download the jar file from this link and add it as a dependency in your application. 

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

Using the code

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.OleObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocOleObject;
import com.spire.doc.fields.DocPicture;

public class InsertOLE {

   
public static void main(String[] args) {

       
//Create a Document instance and load the source document
       
Document doc = new Document();
        doc.loadFromFile(
"C:\\Users\\Administrator\\Desktop\\source.docx");

       
//Get the last section
       
Section section = doc.getLastSection();

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

       
//Load an image which will display as an icon representing the embedded document
       
DocPicture wordIcon = new DocPicture(doc);
        wordIcon.loadImage(
"C:\\Users\\Administrator\\Desktop\\ms-word-icon.png");

       
//Insert a Word document to the source document as an OLE object
        
par.appendOleObject("C:\\Users\\Administrator\\Desktop\\report.docx", wordIcon, OleObjectType.Word_Document);

       
//Save to another file
       
doc.saveToFile("EmbedDocument.docx", FileFormat.Docx_2013
);
    }
}

Output

Write a comment

Comments: 0