News Category

Insert an External File into Word Documents in Java

2020-11-17 06:29:52 Written by  support iceblue
Rate this item
(0 votes)

Spire.Doc for Java supports embedding an external file (Word, Excel, PowerPoint, PDF, picture, video, etc.) in Word documents as an OLE object. This article gives you an example of how to insert a PDF file into a Word document.

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 object and load a Word 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 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);
    }
}

Insert an External File into Word Documents in Java

Additional Info

  • tutorial_title:
Last modified on Tuesday, 31 August 2021 09:24