Saturday, June 19, 2010

Progmatically Using Colums from PageLayout Tab

Progrmatically using Colum from page layout from Word2007 with C#
Add Video
Requirement:-

Visual Studio 2008
Vsto

Let start:-

What we do Normally do when we want to use colum in word.

Normal Word

Selection of Colum


When we click on Colum divide in 2 part.

Now We do same think in C#

Image 1 Remain same
Code do the Colum in C#

public void Pagesetuptest()
{


if (this.ActiveWindow.View.SplitSpecial != WdSpecialPane.wdPaneNone)
{
this.ActiveWindow.Panes[2].Close();
}
if (this.ActiveWindow.View.Type != WdViewType.wdPrintView)
{
this.ActiveWindow.ActivePane.View.Type = WdViewType.wdPrintView;
}


Selection mysel = this.ActiveWindow.Selection;
mysel.PageSetup.TextColumns.SetCount(2);
mysel.PageSetup.TextColumns.EvenlySpaced = -1;
mysel.PageSetup.TextColumns.LineBetween = -1;
}



Output




Sunday, June 13, 2010

Ribbion XML and window for

Loading Winform from ribbion Xml in vsto2007

So Let Start...

Requirement :-
Vs2008(vsto)
and Bit of interest

Start:-

For simple Ribbion customization in Vsto..

http://msdn.microsoft.com/en-us/library/aa942955.aspx

Chk The above link.

Know we will START with loading a WIN FORM ribbion and do the same functionality as in above link.


Know Once u ad Modify the Follwing Files MyRibbon.xml,MyRibbon.cs,ThisAddIn.cs

MyRibbion.xml

>?xml version="1.0" encoding="UTF-8"?&lft
>customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
>ribbon>
>tabs>
>tab idMso="TabAddIns">
>group id="ContentGroup" label="Content">
>button id="Loadform" label="Load Form"
screentip="Load Form"
onAction="LoadForm"
supertip="Load Form "/>

>/group>
>/tab>

>/tabs>
>/ribbon>
>/customUI>


MyRibbon.cs
namespace NewRibbionTest
{
[ComVisible(true)]
public class MyRibbon : Office.IRibbonExtensibility
{
private Office.IRibbonUI ribbon;

public MyRibbon()
{
}

/// This Functin is called from Ribbion and Load the win form
public void LoadForm(Office.IRibbonControl control) { MyTable mytable = new MyTable(); mytable.ShowDialog(); }




#region IRibbonExtensibility Members

public string GetCustomUI(string ribbonID)
{
return GetResourceText("NewRibbionTest.MyRibbon.xml");
}

#endregion

#region Ribbon Callbacks
//Create callback methods here. For more information about adding callback methods, select the Ribbon XML item in Solution Explorer and then press F1

public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
}

#endregion

#region Helpers

private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourcereader =" new" style="font-weight: bold;">ThisAddIn.cs

protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return new MyRibbon();
}

Now addding Window form in project and some code

Code Below:-


private void button1_Click(object sender, EventArgs e)
{
object missing = System.Type.Missing; Range currentRange = Globals.ThisAddIn.Application.Selection.Range; Table newTable = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add( currentRange, 3, 4, ref missing, ref missing); // Get all of the borders except for the diagonal borders. Microsoft.Office.Interop.Word.Border[] borders = new Border[6]; borders[0] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft]; borders[1] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight]; borders[2] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop]; borders[3] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom]; borders[4] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal]; borders[5] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical]; // Format each of the borders. foreach (Border border in borders) { border.LineStyle = WdLineStyle.wdLineStyleSingle; border.Color = WdColor.wdColorBlue; } this.Hide();

}

private void button2_Click(object sender, EventArgs e)
{
Range currentRange = Globals.ThisAddIn.Application.Selection.Range; currentRange.Text = "This text was added by the Win form."; this.Hide();
}

When you click On Insert Ribbion Button You will get the follwing output












Creating Water Mark using TextBox In word2007

Code :-

private void AddWatermark(string WatermarkText)
{
object missing = System.Type.Missing;






Word.Template mytemplate = (Word.Template)Globals.ThisAddIn.Application.ActiveDocument.get_AttachedTemplate();

// Word.Document mydoc = (Word.Document)Globals.ThisAddIn.Application.ActiveDocument;

Word.Selection Selection = mytemplate.Application.Selection;


Word.Shape wmShape;

//Select the section

// mytemplate.Application.Selection.Range.Select();

mytemplate.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader ;


//Create the watermar shape

string strXml = Selection .get_XML(false);


int totallenght = WatermarkText.Length;

wmShape = Selection.HeaderFooter.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationVertical, 0, 0, 0, 0, ref missing);


//Set all of the attributes of the watermark
string strName = "";



object shapeName = "AvinashTiwari";
string strname = "";
try
{
strname = Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Name;

Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Delete();
}
catch (Exception ex)
{
}


wmShape.Select(ref missing);

wmShape.Name = "AvinashTiwari";



wmShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

wmShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;



//U may Use // wmShape.TextFrame.TextRange.Text = WatermarkText;
//TextRange also


// wmShape.Fill.Solid();
wmShape.TextFrame.TextRange.FormattedText.Text = WatermarkText;

wmShape.TextFrame.TextRange.FormattedText.Font.Name = "Arial";
wmShape.TextFrame.TextRange.FormattedText.Font.Bold = 1;
wmShape.TextFrame.TextRange.FormattedText.Font.Size = 14;
wmShape.TextFrame.TextRange.FormattedText.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkRed;

// wmShape.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorDarkRed;




float worddocheight = wmShape.Height;

wmShape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;

wmShape.Height = mytemplate.Application.InchesToPoints(worddocheight);

wmShape.Width = mytemplate.Application.InchesToPoints(12.0f);

wmShape.WrapFormat.AllowOverlap = -1; //true

wmShape.WrapFormat.Side = Word.WdWrapSideType.wdWrapBoth;

wmShape.WrapFormat.Type = Word.WdWrapType.wdWrapNone; //3

wmShape.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionRightMarginArea;

wmShape.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;

wmShape.Left = (float)Word.WdShapePosition.wdShapeLeft ;

//set focus back to document

mytemplate.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;



}

Saturday, June 12, 2010

Reading Header part in Vsto

Code Snippet..


public void XMLRead()
{
try
{
const string mydoc = @"E:\s\WordDocument2.docx";

string xmlstring = "";

using (WordprocessingDocument wdDoc =
WordprocessingDocument.Open(mydoc, false))
{
foreach (HeaderPart hp in wdDoc.MainDocumentPart.HeaderParts)
{
XElement ele = XElement.Load(
XmlReader.Create(hp.GetStream())
);
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
// Console.WriteLine(ele.Descendants(w + "tbl").Count().ToString());
// Console.WriteLine(ele.ToString());
xmlstring = ele.ToString();

}
}

// Console.WriteLine(xmlstring);

StringBuilder output = new StringBuilder();




String xmlString = xmlstring;


string Id = "";
string txtpathvaslue = "";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("v:shape");
// reader.MoveToFirstAttribute();
Id = reader.GetAttribute("id");
output.AppendLine("The genre value: " + Id);


reader.ReadToFollowing("v:textpath");
txtpathvaslue = reader.GetAttribute("string");
output.AppendLine("Content of the title element: " + txtpathvaslue);
}

Console.WriteLine("Id " + Id + " = TxtPath " + txtpathvaslue);



/**********Same thing using Linq to Xml***************/

TextReader tr = new StringReader(xmlString);

TextReader tr2 = new StringReader(xmlString);

XDocument doc = XDocument.Load((new XmlTextReader(tr)));
var query = doc.Element("whdr")
.Element("wp")
.Element("wr")
.Element("wpict")
.Element("vshape")
.Attributes("id");

foreach (XAttribute result in query)
Console.WriteLine(result.Name + " = " + result.Value);



XDocument doc1 = XDocument.Load((new XmlTextReader(tr2)));
var query1 = doc1.Element("whdr")
.Element("wp")
.Element("wr")
.Element("wpict")
.Element("vshape")
.Element("vtextpath")
.Attributes("string");

foreach (XAttribute result1 in query1)
Console.WriteLine(result1.Name + " = " + result1.Value);



/***************************************************/


}
catch (Exception e1)
{
Console.Write(e1.Message);
}

Console.Read();

}

Thursday, June 10, 2010

Watermarking Using Vsto

I found this very Intersting Code about water marking in Word using C#.

I found the code on Net So I like to It modfided for My requirement and I am shareing..

Dnot ask link it was some were in MSDN Blog or some where...


Let The Code start:-

private void AddWatermark(string WatermarkText)
{

Word.Selection Selection = ThisApplication.Selection;

Word.Shape wmShape;

//Select the section

this.Sections[1].Range.Select();

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekCurrentPageHeader;

//Create the watermar shape

wmShape = Selection.HeaderFooter.Shapes.AddTextEffect(

Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,

WatermarkText, "Times New Roman", 1,

Microsoft.Office.Core.MsoTriState.msoFalse,

Microsoft.Office.Core.MsoTriState.msoFalse,

0, 0, ref missing);

//Set all of the attributes of the watermark
string strname ="";

try
{
strname = Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Name;

Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Delete();
}
catch (Exception ex)
{
}


wmShape.Select(ref missing);

wmShape.Name = "Avinash Tiwari";

wmShape.TextEffect.NormalizedHeight = Microsoft.Office.Core.MsoTriState.msoFalse;

wmShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

wmShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

wmShape.Fill.Solid();

wmShape.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorGray25;

wmShape.Fill.Transparency = 0.5f;

wmShape.Rotation = 90.0f;

wmShape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;

wmShape.Height = ThisApplication.InchesToPoints(2.82f);

wmShape.Width = ThisApplication.InchesToPoints(5.64f);

wmShape.WrapFormat.AllowOverlap = -1; //true

wmShape.WrapFormat.Side = Word.WdWrapSideType.wdWrapBoth;

wmShape.WrapFormat.Type = Word.WdWrapType.wdWrapNone; //3

wmShape.RelativeHorizontalPosition =

Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionRightMarginArea;

wmShape.RelativeVerticalPosition =

Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage
;

wmShape.Left = (float)Word.WdShapePosition.wdShapeCenter;

wmShape.Top = (float)Word.WdShapePosition.wdShapeCenter;



//set focus back to document

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekMainDocument;

}



private void DeleteWatermark()
{

Word.Selection Selection = ThisApplication.Selection;

//Select the section

this.Sections[1].Range.Select();

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekCurrentPageHeader;

object shapeName = "PowerPlusWaterMarkObject1";

Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Delete();

//set focus back to document

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekMainDocument;

}



private void AddWM_Click(object sender, EventArgs e)
{

try
{

AddWatermark("Hello World");

}

catch (Exception ex)
{

MessageBox.Show(ex.Message);

}

}



private void DeleteWm_Click(object sender, EventArgs e)
{

try
{

DeleteWatermark();

}

catch (Exception ex)
{

MessageBox.Show(ex.Message);

}

}

Sunday, June 6, 2010

Writing Autotext Entries in Vsto

Finding AutoText Enties from word2007 and Writing on Selected Range
Requirement:-
Vs2oo8(Vsto)
Word
and Bit of Interest

Let Start :-


Go to -- Insert Tab -- Quick parts -- Building Block and U will See some What Image Like That


Know Double Click on Name --- U will See The window note Down Name
Know put the Code


Code:-

Word.Template template = (Word.Template)this.Application.ActiveDocument.get_AttachedTemplate();

//Adding name property of AutoText in This cas I have "Word_auto_text_Avinash"
//and Output would be "Avinash"
object agendaObj = "Word_auto_text_Avinash";
object richText = true;

Word.Range range2 = this.Paragraphs[1].Range;

Word.AutoTextEntry agenda = template.AutoTextEntries.get_Item(ref agendaObj);
agenda.Insert(range2, ref richText);

Output:-

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