Set Word 2010 document margins from C#

10.6k views Asked by At

I want to set the margins on a Word document I'm creating using automation from code in C#.

I've started the process using ActiveDocument.TopMargin = but I cannot find the C# code similar to the vb Word.InchesToPoint(.5) Any help would be greatly appreciated

3

There are 3 answers

2
gideon On

You have to get the instance of the Word application:

Word.Application oWord = new Word.Application();
oWord.InchesToPoints((float)0.5);

See the reference : http://msdn.microsoft.com/en-us/library/ff197549.aspx

0
RCam On

Sometimes the simplest way works. This line of code solved the problem

oWord.ActiveDocument.PageSetup.TopMargin = (float)50;
1
John Kurtz On

You can use the Word Application object's InchesToPoints method like this:

        Word.Application wrdApplication = new Word.Application();
        Word.Document wrdDocument;
        wrdApplication.Visible = true;
        wrdDocument = wrdApplication.Documents.Add();
        wrdDocument.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
        wrdDocument.PageSetup.TopMargin = wrdApplication.InchesToPoints(0.5f);
        wrdDocument.PageSetup.BottomMargin = wrdApplication.InchesToPoints(0.5f);
        wrdDocument.PageSetup.LeftMargin = wrdApplication.InchesToPoints(0.5f);
        wrdDocument.PageSetup.RightMargin = wrdApplication.InchesToPoints(0.5f);

Or if you like, you can make your own...

    private float InchesToPoints(float fInches)
    {
        return fInches * 72.0f;
    }

It could be used in something like this:

        Word.Application wrdApplication = new Word.Application();
        Word.Document wrdDocument;
        wrdDocument = wrdApplication.Documents.Add();
        wrdDocument.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
        wrdDocument.PageSetup.TopMargin = InchesToPoints(0.5f); //half an inch in points
        wrdDocument.PageSetup.BottomMargin = InchesToPoints(0.5f);
        wrdDocument.PageSetup.LeftMargin = InchesToPoints(0.5f);
        wrdDocument.PageSetup.RightMargin = InchesToPoints(0.5f);
        wrdApplication.Visible = true;

Word uses 72 points per inch in its spacing.