Insert an External File into Word Documents Using Java

Andrew Wilson
2 min readMay 24, 2021

This article will introduce how to insert a PDF file into a Word document by using Free Spire.Doc for Java. With this free Java library you can also embed other external files such as Word, Excel, PowerPoint, PDF, picture, video to Word documents as an OLE object.

Installation
Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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>3.9.0</version>
</dependency>
</dependencies>

Sample 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.DocPicture;

public class InsertOLE {

public static void main(String[] args) {

//Create a Document object and load a Word document
Document doc = new Document();
doc.loadFromFile("Input 1.docx");

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

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

//Load an image which will be inserted to Word document representing the embedded file
DocPicture pdfIcon = new DocPicture(doc);
pdfIcon.loadImage("C:\\Users\\Administrator\\Desktop\\pdf_icon.jpg");

//Insert a PDF file to the Word document as an OLE object
par.appendOleObject("C:\\Users\\Administrator\\Desktop\\report.pdf", pdfIcon, OleObjectType.Adobe_Acrobat_Document);

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

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.