代码之家  ›  专栏  ›  技术社区  ›  Jason

MS Word、OpenXML、页面设置、方向和4_方向边距

  •  2
  • Jason  · 技术社区  · 8 年前

    我用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

    我想改变它的方向,从纵向->景观和设置其边际较小。

    工艺前;

    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 回复  |  直到 8 年前
        1
  •  5
  •   petelids    8 年前

    你需要使用 SectionProperties , PageSize PageMargin

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