2017-07-10 73 views
1

我用OpenXML製作了這個文檔。。我正在學習OpenXML。哦..這是如此困難。MS Word,OpenXML,PageSetup,Orientation和4-directional Margins

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

我想從縱向改變其方向 - >景觀並設置其利潤率更小。

處理前;

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領域,它是完全不同的。

我可以提供一些提示嗎?

問候

回答

2

您需要使用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.27釐米大約是36分,這是720分的二十分之一。

+0

嗚..看起來不錯。我現在要嘗試一下。謝謝.. – Jason

+0

工作..是的..尼斯,真好。再次感謝。 – Jason

+0

謝謝@Jason我很高興能幫上忙。 – petelids