DOCX

页面布局

配置页面尺寸、方向、页边距、分栏和分节符

通过 Section 属性控制文档布局。每个文档可以有多个具有不同布局的节。

页面尺寸和方向

import { Document, Paragraph, SectionType } from "@office-open/docx";

const doc = new Document({
    sections: [
        // 纵向 A4
        {
            properties: {
                page: {
                    size: { width: 11906, height: 16838, orientation: "portrait" },
                    margins: {
                        top: 1440,
                        bottom: 1440,
                        left: 1440,
                        right: 1440,
                    },
                },
            },
            children: [new Paragraph("Portrait page")],
        },
        // 横向 A4
        {
            properties: {
                page: {
                    size: { width: 16838, height: 11906, orientation: "landscape" },
                },
            },
            children: [new Paragraph("Landscape page")],
        },
    ],
});

页边距

properties: {
  page: {
    margins: {
      top: 1440,     // 1 英寸(twip 单位)
      bottom: 1440,
      left: 1440,
      right: 1440,
      gutter: 0,     // 装订线
      header: 720,   // 页眉距顶部距离
      footer: 720,   // 页脚距底部距离
    },
  },
},

分栏

创建多栏布局:

properties: {
  page: {
    columns: {
      count: 2,
      space: 708,  // 栏间距(twip 单位)
    },
  },
},

分节符

控制节的过渡方式:

import { SectionType } from "@office-open/docx";

// 每个节可以指定其分隔类型
{
  properties: {
    type: SectionType.CONTINUOUS,    // 不分页
    // type: SectionType.NEXT_PAGE,  // 默认 — 新页面
    // type: SectionType.EVEN_PAGE,  // 下一偶数页
    // type: SectionType.ODD_PAGE,   // 下一奇数页
  },
  children: [...],
},

页面边框

properties: {
  page: {
    borders: {
      top: { style: "single", size: 6, color: "000000", space: 24 },
      bottom: { style: "single", size: 6, color: "000000", space: 24 },
      left: { style: "single", size: 6, color: "000000", space: 24 },
      right: { style: "single", size: 6, color: "000000", space: 24 },
    },
  },
},
Copyright © 2026