You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用docx.js(JS/TS)生成docx文档时无法设置横向布局

解决docx库设置文档横向无效的问题
  • 先将docx库升级到最新稳定版本,部分旧版本存在页面方向配置的兼容性问题。
  • 仅设置orientation不足以让Word正确识别横向,需要同时指定对应横向的页面尺寸——因为默认页面尺寸是为纵向设计的。以下是正确的TS示例代码:
import { Document, Packer, Paragraph, Section, PageOrientation } from "docx";

const doc = new Document({
    sections: [
        {
            properties: {
                page: {
                    orientation: PageOrientation.LANDSCAPE,
                    size: {
                        width: 16838, // A4横向宽度(twip单位)
                        height: 11906, // A4横向高度(twip单位)
                    },
                },
            },
            children: [new Paragraph("横向页面内容")],
        },
    ],
});

// 生成文档buffer
Packer.toBuffer(doc).then(buffer => {
    // 此处可将buffer写入文件或返回给前端
});
  • 若文档包含多个章节,需为每个需要横向显示的章节单独配置上述page属性,避免全局配置失效。
  • 检查生成逻辑:确保sections配置正确传入Document构造函数,不要遗漏或错误嵌套配置项。

内容的提问来源于stack exchange,提问作者Joe Bin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 16:30:43