Introduction
OLE (Object Linking and Embedding) allows applications to link with each other as objects of software. It is often used to create
a compound document to collect a variety of elements together,
such as text, sound, image, video, table, application etc.
Microsoft Word enables users to insert OLE objects in documents. After inserting, we can find that the object contents which are created in
another program are available in Word as well.
This article focuses on how to insert an OLE object, which is a PDF document in my example, by using C#, easily and quickly without Microsoft Automation.
Background
In Microsoft Word, there will be an image, which is related to this object contents, shown on a page after inserting an OLE object. For example, the image will be data information in
a worksheet if we insert a Workbook as OLE Object.
By clicking the image, the workbook will pop up and data in it can be modified.
Steps
Step 1: Get Image Source
Declare a new DocPicture and use the picture.LoadImage(Image) method to get
the image which will be displayed on the Word page.
Note: the image is the first page of the PDF document which I want to insert as OLE object. I export the page as
image by using a PDFViewer.
DocPicture picture = new DocPicture(mydoc);
Image image = Image.FromFile(@"E:\PDFImage.jpg");
picture.LoadImage(image);
Step 2: Set Image Size
In order to make image size suitable for the page, I set the image size, including width and height.
picture.Width = 500;
picture.Height = 700;
Step 3: Insert OLE Object
At first, I add a section and a paragraph in the section after creating a new Word document. Then, insert
an OLE Object in this paragraph by invoking the paragraph.AppendOleObject(filePath, DocPicture, and OleOobjectType) method.
DocOleObject obj = para.AppendOleObject(@"E:\work\Documents\PDF\5 Ways " +
@"to Reduce Travel Marketing Costs.pdf", picture,
Spire.Doc.Documents.OleObjectType.AdobeAcrobatDocument);
Full Code Sample
Document mydoc = new Document();
Section mysec = mydoc.AddSection();
Paragraph para = mysec.AddParagraph();
DocPicture picture = new DocPicture(mydoc);
Image image = Image.FromFile(@"E:\PDFImage.jpg");
picture.LoadImage(image);
picture.Width = 500;
picture.Height = 700;
DocOleObject obj = para.AppendOleObject(@"E:\work\Documents\PDF\5 Ways to " +
@"Reduce Travel Marketing Costs.pdf", picture,
Spire.Doc.Documents.OleObjectType.AdobeAcrobatDocument);
mydoc.SaveToFile("DocOLEObject.docx", FileFormat.Docx2010);
System.Diagnostics.Process.Start("DocOLEObject.docx");
After running, we will get results as in the following screenshot:
Conclusion
This article focuses on how to insert an OLE Object (PDF document) in Word by using C# based on a .NET Word component. There are two elements which must
be prepared, OLE Picture and OLE Object file at the beginning. The image can be any image or related to the OLE object contents. Also, we can convert the OLE object to
an image in code.