Saturday, June 5, 2010

Acessing Buliding Block in for Word2007

Acessing Building Block in word 2007

Requriement :-
vs2008
Word2007
and Bit of interest

Code:-

Public void GetBuildingBlock()
{
// Declare variables to hold references to the Word objects.
ApplicationClass wordApplication = null;
Document wordDocument = null;
Template wordTemplate;
BuildingBlock wordBuildingBlock;

// Declare a variable for the path of the new document.
object paramDocPath = @"G:\ALL_TRAINING_MATERIAL\OpenXML\WordTemp\Test.docx";

// Declare variables for the building block properties.
WdBuildingBlockTypes paramBBType = WdBuildingBlockTypes.wdTypeWatermarks;

//Category
// object paramBBCategory = "Building Block Tests";
object paramBBCategory = "Urgent";

//Name
// object paramBBName = "Header Test";
object paramBBName = "ASAP 2";

// Declare variables to help with methods that accept optional
// and by reference parameters.
object paramMissing = Type.Missing;
object paramTemplateIndex = 1;
object paramFalse = false;

try
{
// Start an instance of Word.
wordApplication = new ApplicationClass();

// Create a new document.
wordDocument = wordApplication.Documents.Add(ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing);

// Load the "Building Blocks.dotx" template.
// After calling LoadBuildingBlocks Building Blocks.dotx will be Templates(1).
wordApplication.Templates.LoadBuildingBlocks();
wordTemplate = wordApplication.Templates.get_Item(ref paramTemplateIndex);

// Access the "Header Test" custom headers building block
// through its type, category, and name.
wordBuildingBlock =
wordTemplate.BuildingBlockTypes.Item(paramBBType)
.Categories.Item(ref paramBBCategory)
.BuildingBlocks.Item(ref paramBBName);

// Insert the building block into the primary header of the first
// section of the document.
wordBuildingBlock.Insert(wordDocument.Sections[1]
.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range,
ref paramMissing);

// Save the document.
wordDocument.SaveAs(ref paramDocPath, ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing);
}
catch (Exception ex)
{
// Respond to the error.
Console.WriteLine(ex.Message);
}
finally
{
// Release references to the Word objects.
wordBuildingBlock = null;
wordTemplate = null;

// Close and release the Document object.
if (wordDocument != null)
{
((_Document)wordDocument).Close(ref paramFalse, ref paramMissing, ref paramMissing);
wordDocument = null;
}

// Quit Word and release the ApplicationClass object.
if (wordApplication != null)
{
wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
wordApplication = null;
}

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

No comments:

Post a Comment