Others

Others (8)

A theme is a set of colors, fonts, and effects that determines the overall look of your Word document. Suppose you have a document which is neat and stylish, you’d like to copy contents of a section to another document without losing the theme and style. You can clone the theme to destination file using CloneThemeTo method.

Step 1: Create a Document object and load a sample Word file.

Document doc = new Document();
doc.LoadFromFile("theme.docx");

Step 2: Create a new Word document.

Document newWord = new Document();

Step 3: Clone default style, theme, compatibility from the source file to destination document.

doc.CloneDefaultStyleTo(newWord);
doc.CloneThemesTo(newWord);
doc.CloneCompatibilityTo(newWord);

Step 4: Add the cloned section to destination document.

newWord.Sections.Add(doc.Sections[0].Clone());

Step 5: Save the file.

newWord.SaveToFile("result.docx", FileFormat.Docx);

Output:

Preserve Theme When Copying Sections from One Word Document to Another in C#

Full Code:

Document doc = new Document();
doc.LoadFromFile("theme.docx");

Document newWord = new Document();     
doc.CloneDefaultStyleTo(newWord);
doc.CloneThemesTo(newWord);
doc.CloneCompatibilityTo(newWord);
newWord.Sections.Add(doc.Sections[0].Clone());

newWord.SaveToFile("result.docx", FileFormat.Docx);
Thursday, 08 September 2016 03:50

How to Extract OLE Objects from a Word Document

Written by support iceblue

Sometimes, we need to extract the OLE Objects that are embedded in a word document. With Spire.Doc, we can easily achieve this task with a few lines of code. This article explains how to extract the embedded PDF document and Excel workbook from a word document using Spire.Doc and C#.

Below is the screenshot of the word document:

How to Extract OLE Objects from a Word Document

Detail steps:

Step 1: Instantiate a Document object and load the word document.

Document doc = new Document();
doc.LoadFromFile("OleObject.docx");

Step 2: Traverse through the word document, find the Ole Objects, then get the Object type of each Ole Object to determine if the Ole Object is PDF document or Excel workbook and write the native data of the Ole object into a new PDF document or an Excel workbook.

//Traverse through all sections of the word document           
foreach (Section sec in doc.Sections)
{
    //Traverse through all Child Objects in the body of each section
    foreach (DocumentObject obj in sec.Body.ChildObjects)
    {
        if (obj is Paragraph)
        {
            Paragraph par = obj as Paragraph;
            //Traverse through all Child Objects in Paragraph
            foreach (DocumentObject o in par.ChildObjects)
            {
                //Find the Ole Objects and Extract
                if (o.DocumentObjectType == DocumentObjectType.OleObject)
                {
                    DocOleObject Ole = o as DocOleObject;
                    string s = Ole.ObjectType;
                    //If s == "AcroExch.Document.11", means it’s a PDF document
                    if (s == "AcroExch.Document.11")
                    {
                        File.WriteAllBytes("Result.pdf", Ole.NativeData);
                    }
                    //If s == " Excel.Sheet.12", means it’s an Excel workbook
                    else if (s == "Excel.Sheet.12")
                    {
                        File.WriteAllBytes("Result.xlsx", Ole.NativeData);
                    }
                }
            }
        }
    }
}

Below is the screenshot of the extracted PDF file and Excel workbook after running the code:

How to Extract OLE Objects from a Word Document

How to Extract OLE Objects from a Word Document

Full codes:

using System.IO;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace Extract_OLEObjects_from_Word
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("OleObject.docx");
        
            foreach (Section sec in doc.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    if (obj is Paragraph)
                    {
                        Paragraph par = obj as Paragraph;
                        foreach (DocumentObject o in par.ChildObjects)
                        {
                            if (o.DocumentObjectType == DocumentObjectType.OleObject)
                            {
                                DocOleObject Ole = o as DocOleObject;
                                string s = Ole.ObjectType;
                                if (s == "AcroExch.Document.11")
                                {
                                    File.WriteAllBytes("Result.pdf", Ole.NativeData);
                                }
                                else if (s == "Excel.Sheet.12")
                                {
                                    File.WriteAllBytes("Result.xlsx", Ole.NativeData);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Wednesday, 12 August 2015 02:23

How to Embed Media File in Word in C#, VB.NET

Written by support iceblue

Spire.Doc supports to insert any type of file such as Excel, PDF, PowerPoint and etc, as OLE object into a Word document. In this article, you'll learn how to add a media file (audio or video) to a Word document using Spire.Doc in C#, VB.NET.

In the class of DocOleObject, a method named AppendOleObject(Stream oleStream, DocPicture olePicture, string fileExtension) is available for users to insert media file with the extension of mp3, mp4, avi or any other format into a Word document. The three parameters in this method represent:

  • oleStream: The OLE file stream.
  • olePicture: The image (icon) that is displayed in Word to show the OLE object.
  • fileExtension: The file extension.

Code Snippet:

Step 1: Initialize a new instance of Document class and add a new section.

Document doc = new Document();
Section section = doc.AddSection();

Step 2: Add a new paragraph, append some formatted text into the paragraph.

Paragraph para1 = section.AddParagraph();
para1.AppendText("Double click the PLAY button to view the video file");
ParagraphStyle style1 = new ParagraphStyle(doc);
style1.Name = "Style";
style1.CharacterFormat.FontName = "Calibri";
style1.CharacterFormat.FontSize = 15;
style1.CharacterFormat.Bold = true;
style1.CharacterFormat.TextColor = Color.Red;
doc.Styles.Add(style1);
para1.ApplyStyle(style1.Name);

Step 3: Add another paragraph, append a video file as OLE object into the paragraph.

Paragraph para2 = section.AddParagraph();
Stream s = File.OpenRead("media.mp4");
DocPicture pic = new DocPicture(doc);
pic.LoadImage(Image.FromFile("button.png"));
para2.AppendOleObject(s, pic, "mp4");

Step 4: Save the view the file.

doc.SaveToFile("Result.docx", FileFormat.Docx2010);
System.Diagnostics.Process.Start("Result.docx");

Output:

How to Embed Media File in Word in C#, VB.NET

Full Code:

[C#]
//create a new Word document and insert section
Document doc = new Document();
Section section = doc.AddSection();
//add a paragraph and append some text
Paragraph para1 = section.AddParagraph();
para1.AppendText("Double click the PLAY button to view the video file");
ParagraphStyle style1 = new ParagraphStyle(doc);
style1.Name = "Style";
style1.CharacterFormat.FontName = "Calibri";
style1.CharacterFormat.FontSize = 15;
style1.CharacterFormat.Bold = true;
style1.CharacterFormat.TextColor = Color.Red;
doc.Styles.Add(style1);
para1.ApplyStyle(style1.Name);
//add another paragraph, append video file as OLE object in Word
Paragraph para2 = section.AddParagraph();
Stream s = File.OpenRead("media.mp4");
DocPicture pic = new DocPicture(doc);
pic.LoadImage(Image.FromFile("button.png"));
para2.AppendOleObject(s, pic, "mp4");
//save and view the file
doc.SaveToFile("Result.docx", FileFormat.Docx2010);
System.Diagnostics.Process.Start("Result.docx");
[VB.NET]
'create a new Word document and insert section
Dim doc As New Document()
Dim section As Section = doc.AddSection()
'add a paragraph
Dim para1 As Paragraph = section.AddParagraph()
para1.AppendText("Double click the PLAY button to view the video file")
Dim style1 As New ParagraphStyle(doc)
style1.Name = "Style"
style1.CharacterFormat.FontName = "Calibri"
style1.CharacterFormat.FontSize = 15
style1.CharacterFormat.Bold = True
style1.CharacterFormat.TextColor = Color.Red
doc.Styles.Add(style1)
para1.ApplyStyle(style1.Name)
'add another paragraph, append video file as OLE object in Word
Dim para2 As Paragraph = section.AddParagraph()
Dim s As Stream = File.OpenRead("media.mp4")
Dim pic As New DocPicture(doc)
pic.LoadImage(Image.FromFile("button.png"))
para2.AppendOleObject(s, pic, "mp4")
'save and view the file
doc.SaveToFile("Result.docx", FileFormat.Docx2010)
System.Diagnostics.Process.Start("Result.docx")

Spire.Doc for .NET, a professional .NET word component to fast generate, open, modify and save Word documents without using MS Office Automation, enables users to set superscript and subscript in word document by using C#.NET. This guide introduces a method how to set superscript and subscript via Spire.Doc for .NET.

The screenshot below presents result after setting superscript and subscript in word:

Set superscript and subscript in Word document

There is a guide to introduce the detail method to set superscript and subscript in word document.

The main steps of method are:

Step 1: create a document and add new paragraph.

Document document = new Document(@"Blank.doc");
Paragraph paragraph = document.LastSection.AddParagraph();

Step 2: use the range1.CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SuperScript to set suberscript.

paragraph.AppendText("E = mc");
TextRange range1 = paragraph.AppendText("2");
//supperscript
range1.CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SuperScript;

Step 3: use range2.CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript to set subscript.

paragraph.AppendText("F");
TextRange range2 = paragraph.AppendText("n");
//subscript
range2.CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

Step 4: save the document.

document.SaveToFile("result.docx", FileFormat.Docx);

Download and install Spire.Doc for .NET and use below code to experience this method to set superscript and subscript in word document.

The full code:

[C#]
using System;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace SubSuperScript
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document(@"Blank.doc");
            Paragraph paragraph = document.LastSection.AddParagraph();
            paragraph.AppendText("E = mc");
            TextRange range1 = paragraph.AppendText("2");

            //supperscript
            range1.CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SuperScript;

            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("F");
            TextRange range2 = paragraph.AppendText("n");

            //subscript
            range2.CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

            paragraph.AppendText(" = F");
            paragraph.AppendText("n-1").CharacterFormat.SubSuperScript =Spire.Doc.Documents.SubSuperScript.SubScript;
            paragraph.AppendText(" + F");
            paragraph.AppendText("n-2").CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

            //fontsize
            foreach (var i in paragraph.Items)
            {
                if (i is TextRange)
                {
                    (i as TextRange).CharacterFormat.FontSize = 36;
                }
            } 
            document.SaveToFile("result.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("result.docx");
        }
      }
}

If you couldn't successfully use the Spire.Doc please refer the Spire.Doc Quick Start which can guide you quickly use the Spire.Doc.

Word Marco is widely used to record the operation that needs to be done repeatedly and you can apply it with only a single click. It can save lots of time for you. It is not an easy work to load a word document with Macro in C# and sometimes, you need to remove the Marco in the word documents in C#. This article will focus on demonstrate how to load and save word document with Marco, and clear the Marco by using Spire.Doc in C# in simple lines of codes.

First, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer.

Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Here comes to the steps.

Step 1: Load and save the document with Marco. Spire.Doc for .NET supports .doc, .docx(Word 97-2003) document with macros and .docm(Word 2007 and Word 2010) document.

//Loading document with macros.
document.LoadFromFile(@"D:\Macros.docm", FileFormat.Docm);
//Save docm file.
document.SaveToFile("Sample.docm", FileFormat.Docm);

Load and save word with Macro

Step 2: Clear the Marco in word document. With Spire.Doc, you only need one line of code to remove all the Marcos at one time.

//Removes the macros from the document
document.ClearMacros();
//Save docm file.
document.SaveToFile("Sample.docm", FileFormat.Docm);

Here comes to the screenshot which has removed the Marco in word document.

Remove Macro

Monday, 29 October 2012 01:11

Create Barcode in Word in C#, VB.NET

Written by support iceblue

Barcode is formed by several blanks and black stripes with a specified order. It presents the brief information of one product, including manufacturer, product name, category, price etc. At present, barcode is widely used in commodity circulation. Also, people can create barcode in Word and print.

Spire.Doc for .NET, a stand-alone professional .NET Word component, enables users to create barcode in Word by using C#, VB.NET. So, this guide will show you the method about how to create via Spire.Doc for .NET.

At first, you need to install barcode font on your system. Then, add barcode text through invoking p.AppendText(string) method and then set text format properties for it, such as FontName, FontSize, TextColor etc. After running, we can get result as following screenshot.

Create Word Barcode

Download and install Spire.Doc for .NET and then use the following code to create barcode in Word.

[C#]
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace WordBarcode
{
    class BarCode
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();
            Paragraph p = document.AddSection().AddParagraph();

            //Add Barcode and Set Format
            TextRange txtRang = p.AppendText("H63TWX11072");
            txtRang.CharacterFormat.FontName = "C39HrP60DlTt";
            txtRang.CharacterFormat.FontSize = 80;
            txtRang.CharacterFormat.TextColor = Color.SeaGreen;

            //Save and Launch
            document.SaveToFile("barcode.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("barcode.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace WordBarcode
    Friend Class BarCode
        Shared Sub Main(ByVal args() As String)
            'Create Document
            Dim document As New Document()
            Dim p As Paragraph = document.AddSection().AddParagraph()

            'Add Barcode and Set Format
            Dim txtRang As TextRange = p.AppendText("H63TWX11072")
            txtRang.CharacterFormat.FontName = "C39HrP60DlTt"
            txtRang.CharacterFormat.FontSize = 80
            txtRang.CharacterFormat.TextColor = Color.SeaGreen

            'Save and Launch
            document.SaveToFile("barcode.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("barcode.docx")
        End Sub
    End Class
End Namespace

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Thursday, 23 August 2012 06:30

Insert OLE Object in Word in C#, VB.NET

Written by support iceblue

Word OLE (Object Linking and Embedding) object is used to make contents, created in one program, available in Word document. For example, users can insert an Excel worksheet in a Word document.

Both Linked object and Embedded object can be used between Word and other programs. The data of Embedded objects is saved in Word and should be updated manually, while data of Linked object remains as separate file and will be updated when source data is changed.

Spire.Doc for .NET , a professional component to manipulate Word documents with .NET, enables users to insert OLE objects in Word by using C#/VB.NET. This guide will show you how to insert one kind of OLE objects, Linked objects (an Excel Worksheet) in Word.

Users can invoke paragraph.AppendOleObject(string pathToFile, olePicture, OleObjectType) method to insert OLE objects in Word. The parameters, olePicture and OleObjectType are properties of DocOleObject class which is provided by Spire.Doc for .NET.

The following steps present details to insert OLE Objects in Word. The following demonstrate a document before insert the OLE Object into Word, and at the bottom, you can find the result screenshot after inserting. Before starting with the steps, download and install Spire.Doc for .NET on system.

Insert Word OLE Objects

Code Detail:

Step 1: Define a GetExcelImage(string ExcelFile) method to get olePicture. Actually, the olePicture is image of data information in original Excel worksheet. The image is generated from Excel through Spire.XLS for .NET that will be shown in documents after inserting OLE object in Word. Double click this picture and you can get the original worksheet.

[C#]
 
private static Image GetExcelImage(String ExcelFile)
 {
  //Load Excel File
  Workbook workbook = new Workbook();
  workbook.LoadFromFile(ExcelFile);
  Worksheet sheet = workbook.Worksheets[0];

  //Set Image Range
  int lastRow = sheet.LastRow;
  int lastColumn = sheet.LastColumn;
  return workbook.Worksheets[0].SaveToImage(1, 1, lastRow, lastColumn);
}
[VB.NET]
   
Private Shared Function GetExcelImage(ByVal ExcelFile As String) As Image
  'Load Excel File
  Dim workbook As New Workbook()
  workbook.LoadFromFile(ExcelFile)
  Dim sheet As Worksheet = workbook.Worksheets(0)

  'Set Image Range
  Dim lastRow As Integer = sheet.LastRow
  Dim lastColumn As Integer = sheet.LastColumn
  Return workbook.Worksheets(0).SaveToImage(1, 1, lastRow, lastColumn)
End Function
 

Step 2: Insert OLE object. After adding paragraph in Word document, declare a new DocPicture. Then, use GetExcelImage(string ExcelFile) method which is defined in step 1 to get image source and then use picture.LoadImage(Image) method to load this image. Finally, insert OLE objects.

[C#]
       
para = mysec.AddParagraph();
DocPicture picture = new DocPicture(mydoc);
Image image = GetExcelImage(@"E:\work\Documents\ExcelFiles\Customers.xlsx");//Get Image Source
picture.LoadImage(image);//Load Image
DocOleObject obj = para.AppendOleObject(@"E:\work\Documents\ExcelFiles\Customers.xlsx", picture, Spire.Doc.Documents.OleObjectType.ExcelWorksheet);
[VB.NET]
  
'Insert OLE Object
para = mysec.AddParagraph()
Dim picture As New DocPicture(mydoc)
Dim image As Image = GetExcelImage("E:\work\Documents\ExcelFiles\Customers.xlsx") 'Get Image Source
picture.LoadImage(image) 'Load Image
Dim obj As DocOleObject = para.AppendOleObject("E:\work\Documents\ExcelFiles\Customers.xlsx", picture, Spire.Doc.Documents.OleObjectType.ExcelWorksheet)

After this coding, you can run this application and a result will show up as below:

Insert Word OLE Objects

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Tuesday, 28 December 2010 06:45

How to Traverse a Document Tree

Written by Administrator
Spire.Doc represents a document as a tree, every document element is a node of that tree. Some nodes such as section, paragraph and table may have many child nodes. For example, a section node has several paragraph nodes, a paragraph node has many text nodes and each row is the child node of a table node. And other nodes have no child node, such as text-range, image, form-field.
If a node has child nodes, it should be an instance of Spire.Doc.Interface.ICompositeObject.
If you want to operate all the nodes, you can use the tree navigation method to visit each node.

Document Tree Traversal

The following example demonstrates how to traverse a document tree to collect all nodes and ouput the text of all text-range nodes.
[C#]
using System;
using System.Collections.Generic;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;
using Spire.Doc.Collections;

namespace ExtractText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Open a word document.
            Document document = new Document("Sample.doc");
            IList<IDocumentObject> nodes = GetAllObjects(document);
            foreach (IDocumentObject node in nodes)
            {
                //Judge the object type. 
                if (node.DocumentObjectType == DocumentObjectType.TextRange)
                {
                    TextRange textNode = node as TextRange;
                    Console.WriteLine(textNode.Text);
                }
            }
        }

        private static IList<IDocumentObject> GetAllObjects(Document document)
        {
        
            //Create a list.
            List<IDocumentObject> nodes = new List<IDocumentObject>();
            
            //Create a new queue.
            Queue<ICompositeObject> containers = new Queue<ICompositeObject>();
            
            //Put the document objects in the queue.
            containers.Enqueue(document);
            while (containers.Count > 0)
            {
                ICompositeObject container = containers.Dequeue();
                DocumentObjectCollection docObjects = container.ChildObjects;
                foreach (DocumentObject docObject in docObjects)
                { 
                    nodes.Add(docObject);
                    
                    //Judge the docObject.
                    if (docObject is ICompositeObject)
                    {
                        containers.Enqueue(docObject as ICompositeObject);
                    }
                }
            }

            return nodes;
        }
    }
}
          
[VB.NET]
Imports System
Imports System.Collections.Generic
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Interface
Imports Spire.Doc.Collections

Module Module1

    Sub Main()
        'Open a word document.
        Dim document As New Document("Sample.doc")
        Dim nodes As IList(Of IDocumentObject)() = GetAllObjects(document)
        Dim containers As New Queue(Of ICompositeObject)()

        For Each node As IDocumentObject In nodes
        
            'Judge the object type.
            If (node.DocumentObjectType = DocumentObjectType.TextRange) Then
                Dim textNode As TextRange = node
                Console.WriteLine(textNode.Text)

            End If
        Next
    End Sub
    Function GetAllObjects(ByVal document As Document) As IList(Of IDocumentObject)
        
        'Create a list.
        Dim nodes As New List(Of IDocumentObject)()
        
        'Create a new queue.
        Dim containers As New Queue(Of ICompositeObject)()
        
        'Put the document objects in the queue.
        containers.Enqueue(document)
        While (containers.Count > 0)
            Dim container As ICompositeObject = containers.Dequeue()
            Dim docObjects As DocumentObjectCollection = container.ChildObjects
            For Each docObject As DocumentObject In docObjects
                nodes.Add(docObject)
                
                'Judge the docObject.
                If TypeOf docObject Is ICompositeObject Then
                    containers.Enqueue(TryCast(docObject, ICompositeObject))
                End If
            Next
        End While

        Return nodes
    End Function
End Module