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

时间:2017-07-10 02:43:50

标签: c#-4.0 ms-word openxml

我用OpenXML创建了这个文档。。我正在学习OpenXML。哦......真是太难了。

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

enter image description here

我想从肖像改变其方向 - &gt;景观并将其利润率设置得更小。

在处理之前;

enter image description here

过程后; enter image description here

我可以用这样的VBA代码实现这个目标;

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

但是,当我去OpenXML区域时,情况就完全不同了。

我可以提供一些建议吗?

此致

1 个答案:

答案 0 :(得分:3)

您需要使用SectionPropertiesPageSizePageMargin类,如下所示:

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

请注意,页边距值是以点的二十分之一定义的。 1.27cm大约是36个点,是720点的二十分之一。