MS Word, OpenXML, PageSetup, Orientation and 4_directional Margins

泪湿孤枕 提交于 2019-12-12 19:05:31

问题


I made this document with OpenXML. . I'm learning OpenXML. Oh.. it is so difficult.

MainDocumentPart m = wd.AddMainDocumentPart();
m.Document = new Document();
Body b1 = new Body();
int myCount = 5;
for (int z = 1; z <= myCount; z++)
{
    Paragraph p1 = new Paragraph();
    Run r1 = new Run();
    Text t1 = new Text(
        "The Quick Brown Fox Jumps Over The Lazy Dog  " + z );
    r1.Append(t1);                      
    p1.Append(r1);
    b1.Append(p1);
}
m.Document.Append(b1);

I'd like to change its orientation from portrait -> landscape and to set its margin smaller.

Before process;

After process;

I can achieve this goal with VBA codes like this;

With ActiveDocument.PageSetup
    .Orientation = wdOrientLandscape  
    .TopMargin = CentimetersToPoints(1.27)
    .BottomMargin = CentimetersToPoints(1.27)
    .LeftMargin = CentimetersToPoints(1.27)
    .RightMargin = CentimetersToPoints(1.27)
End With

But, when I go to OpenXML area, it is quite different.

Can I have some tips ?

Regards


回答1:


You need to use the SectionProperties, PageSize and PageMargin classes like so:

using (WordprocessingDocument wd = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document))
{
    MainDocumentPart m = wd.AddMainDocumentPart();
    m.Document = new Document();
    Body b1 = new Body();

    //new code to support orientation and margins
    SectionProperties sectProp = new SectionProperties();
    PageSize pageSize = new PageSize() { Width = 16838U, Height = 11906U, Orient = PageOrientationValues.Landscape };
    PageMargin pageMargin = new PageMargin() { Top = 720, Right = 720U, Bottom = 720, Left = 720U };

    sectProp.Append(pageSize);
    sectProp.Append(pageMargin);
    b1.Append(sectProp);
    //end new code

    int myCount = 5;
    for (int z = 1; z <= myCount; z++)
    {
        Paragraph p1 = new Paragraph();
        Run r1 = new Run();
        Text t1 = new Text(
            "The Quick Brown Fox Jumps Over The Lazy Dog  " + z);
        r1.Append(t1);
        p1.Append(r1);
        b1.Append(p1);
    }
    m.Document.Append(b1);
}

Note that the page margin values are defined in twentieths of a point. 1.27cm is roughly 36 points which is 720 twentieths of a point.



来源:https://stackoverflow.com/questions/45003078/ms-word-openxml-pagesetup-orientation-and-4-directional-margins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!