Insert an External File into Word Documents Using Java

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.

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.


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);

//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);

Sharing Java Code