
docx 库 Document 对象完全指南从零创建 Word 文档与全部配置项详解【免费下载链接】docxEasily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.项目地址: https://gitcode.com/GitHub_Trending/do/docx导读Document是 docx 库中一切 .docx 文件的起点它代表 Word 文档本身所有内容段落、表格、页眉页脚等都被组织进它的sections中最后再通过Packer导出为真实文件。本篇以 docs/usage/document.md 为核心结合仓库源码src/file/file.ts、src/file/core-properties/properties.ts、src/file/settings/settings.ts 等与示例demo/54-custom-properties.ts、demo/60-track-revisions.ts完整覆盖文档创建、元数据属性、背景色、自定义属性、特性开关与兼容性配置读完即可用一行行配置生成带完整元数据与兼容选项的专业 Word 文档。创建你的第一个 DocumentDocument对象是 .docx 之旅的起点它就是你最终生成的 Word 文档本体。所有内容——无论是Paragraph段落、Table表格还是目录——都必须放进sections数组中const doc new docx.Document({ sections: [ { children: [new Paragraph(Hello World)], }, ], });在仓库中这个对外导出的Document类实际上对应 src/file/file.ts 中的File类publicApi注释明确写有 The File class (exported asDocument) is the main entry point for creating DOCX documents。构造时它会完成一整条装配流水线用传入的creator、revision、lastModifiedBy等生成核心属性core properties初始化numbering、comments、customProperties、footnotes、endnotes、settings、styles、media等所有文档部件为word/document.xml、docProps/core.xml、docProps/app.xml、docProps/custom.xml、styles.xml、numbering.xml、footnotes.xml、endnotes.xml、settings.xml、comments.xml建立默认 relationship见addDefaultRelationshipssrc/file/file.ts逐个addSection把每个 section 的children追加到document.xml的 body 中。而真正渲染w:document根元素的是 src/file/document/document.ts它会写入几十个 XML 命名空间声明wpc、mc、r、m、w、w14、w15等见 src/file/document/document-attributes.ts因此生成的文件无需任何额外声明即可被 Word 正确解析。Document.add()方法还可以直接追加段落、表格、目录等块级元素并支持链式调用。Document Properties文档元数据你可以为 Word 文档添加元数据属性它们会显示在 Word 的「文件 信息」面板以及文件属性中const doc new docx.Document({ creator: Dolan Miu, description: My extremely interesting document, title: My Document, subject: Report, keywords: report, annual, finance, sections: [ /* ... */ ], });Metadata Properties元数据属性PropertyTypeDescriptiontitlestringDocument titlesubjectstringDocument subjectcreatorstringAuthor namekeywordsstringKeywords for searchingdescriptionstringDocument description/commentslastModifiedBystringLast person to modifyrevisionnumberRevision number从源码看这些属性由 src/file/core-properties/properties.ts 中的CoreProperties类写出会生成标准的cp:corePropertiesXML 块title→dc:titlesubject→dc:subjectcreator→dc:creatorDublin Core 命名空间keywords→cp:keywordsdescription→dc:descriptionlastModifiedBy→cp:lastModifiedByrevision→cp:revision无论是否传参都会自动追加dcterms:created与dcterms:modified两个时间戳元素类型为xsi:typedcterms:W3CDTFW3C 日期时间格式值为当前时间。另外在 src/file/file.ts 中可以看到三个默认值兜底逻辑creator未提供时默认Un-namedlastModifiedBy默认Un-namedrevision默认1。也就是说即使你不写元数据生成的文件也始终携带合法的核心属性部件。Options by Category按类别速查全部配置Document的完整选项定义在 src/file/core-properties/properties.ts 的IPropertiesOptions类型中与文档表格完全对应。以下是按功能类别整理的配置项。Content Options内容选项PropertyTypeDescriptionsectionsISectionOptions[]Document sectionscommentsICommentsOptionsDocument commentsfootnotesRecordstring, { children: Paragraph[] }FootnotesISectionOptions的完整定义见 src/file/file.ts每个 section 可包含headersdefault/first/even三种、footers同样三种、properties页面大小、边距、方向等节属性以及必填的children内容数组。此外IPropertiesOptions还支持endnotes尾注Recordstring, { children: Paragraph[] }结构与 footnotes 一致相关实现见 src/file/endnotes/endnotes.ts。Styling Options样式选项PropertyTypeDescriptionstylesIStylesOptionsCustom stylesexternalStylesstringExternal XML stylesnumberingINumberingOptionsNumbering definitionsfontsFontOptions[]Embedded fontsdefaultTabStopnumberDefault tab stop (twips)从源码看src/file/file.ts样式装配有三条路径传了externalStyles时会用ExternalStylesFactory解析外部 XML 样式并与默认样式合并只传styles时用DefaultStylesFactory生成并合并自定义样式两者都没传时生成全默认样式。fonts则由FontWrappersrc/file/fonts/font-wrapper.ts负责把字体嵌入文档。defaultTabStop会被写进settings.xml的w:defaultTabStop单位为 twips1 英寸 1440 twips。Document Behavior文档行为PropertyTypeDescriptionbackgroundIDocumentBackgroundOptionsDocument backgroundfeatures{ trackRevisions?: boolean; updateFields?: boolean }Feature flagsevenAndOddHeaderAndFootersbooleanDifferent odd/even headershyphenationIHyphenationOptionsHyphenation settingsevenAndOddHeaderAndFooters会在settings.xml中写入w:evenAndOddHeaders配合 section 里的headers.even/footers.even使用可实现奇偶页不同的页眉页脚详见 docs/usage/headers-and-footers.md。hyphenation支持autoHyphenation自动断词、hyphenationZone断词区twips、consecutiveHyphenLimit连续断词行数上限、doNotHyphenateCaps全大写不参与断词四个子项对应w:autoHyphenation、w:hyphenationZone、w:consecutiveHyphenLimit、w:doNotHyphenateCaps元素见 src/file/settings/settings.ts。Compatibility兼容性PropertyTypeDescriptioncompatibilityICompatibilityOptionsCompatibility settingscompatabilityModeVersionnumberWord version compatibility注意compatabilityModeVersion注意拼写在源码中被标记为 deprecated见 src/file/settings/settings.ts建议改用compatibility.version。两者的关系是compatibility.version ?? compatabilityModeVersion ?? 15即都不传时默认取15。Full list of options完整选项列表PropertyTypeNotessectionsISectionOptions[]OptionaltitlestringOptionalsubjectstringOptionalcreatorstringOptionalkeywordsstringOptionaldescriptionstringOptionallastModifiedBystringOptionalrevisionnumberOptionalexternalStylesstringOptionalstylesIStylesOptionsOptionalnumberingINumberingOptionsOptionalcommentsICommentsOptionsOptionalfootnotesRecordstring, { children: Paragraph[] }OptionalbackgroundIDocumentBackgroundOptionsOptionalfeatures{ trackRevisions?: boolean; updateFields?: boolean; }OptionalcompatabilityModeVersionnumberOptionalcompatibilityICompatibilityOptionsOptionalcustomPropertiesICustomPropertyOptions[]OptionalevenAndOddHeaderAndFootersbooleanOptionaldefaultTabStopnumberOptionalfontsFontOptions[]OptionalhyphenationIHyphenationOptionsOptional这些选项可以随意自由组合也可以一个都不传除sections外全部可选。修改文档背景色给文档设置十六进制背景色非常简单const doc new docx.Document({ background: { color: C45911, }, });从源码看src/file/document/document-background/document-background.tsIDocumentBackgroundOptions除了color十六进制字符串无需#前缀会经hexColorValue校验还支持themeColor如accent1、dark1等主题色枚举、themeShade加深主题色和themeTint减淡主题色后两者为十六进制数值。最终渲染为document.xml中的w:background w:colorC45911/元素并且Settings会自动附带w:displayBackgroundShape/src/file/settings/settings.ts确保 Word 能显示背景形状。Custom Properties自定义属性除了标准元数据还可以添加自定义属性它们同样会出现在 Word 的文档属性面板中const doc new docx.Document({ customProperties: [ { name: Department, value: Engineering, }, { name: Project Code, value: PRJ-2024-001, }, { name: Approved, value: true, }, { name: Version, value: 2.5, }, ], sections: [ /* ... */ ], });自定义属性支持以下值类型string- Text values文本number- Numeric values数值布尔与数字会在写入时转换为字符串boolean- True/false values布尔仓库中的完整示例见 demo/54-custom-properties.ts它同时设置了标准属性creator、title、subject、description和Subtitle、Address两个自定义属性然后通过Packer.toBuffer(doc)写出My Document.docx。从源码看src/file/custom-properties/custom-properties.ts自定义属性被渲染到独立的docProps/custom.xml部件中每个property元素带有固定formatId{D5CDD505-2E9C-101B-9397-08002B2CF9AE}OOXML 自定义属性标准 GUID自增pid从 2 开始源码注释说明这是 Office 规范约定name属性名值统一写为vt:lpwstrvariant type 的 long pointer to wide string。也就是说自定义属性的本质是以Properties为根、vt:类型命名空间承载的键值对集合Word 与 docProps 工具链都能读取。Document Features特性开关features用来启用特殊行为例如修订跟踪Track Changes与字段自动更新const doc new docx.Document({ features: { trackRevisions: true, // Enable track changes updateFields: true, // Update fields (like TOC) when opened }, sections: [ /* ... */ ], });使用目录Table of Contents时建议设置updateFields: true这样文档打开时会自动刷新目录页码。从源码看src/file/file.ts这两个开关最终写入settings.xmltrackRevisions: true→w:trackRevisions/。demo 示例 demo/60-track-revisions.ts 注释明确指出该设置让 Word 在文档生成之后跟踪用户新做的修订而文档中已有的插入/删除文本InsertedTextRun、DeletedTextRun无论是否开启此开关都会保留显示updateFields: true→w:updateFields/指示打开文档时重新计算域TOC、页码等。对应实现在 src/file/settings/settings.ts。更完整的修订功能插入、删除、批注回复等可参考 docs/usage/change-tracking.md。定位单位twips、EMU 与换算API 中涉及定位的参数都基于 OOXML 规范的「1/20 点」twips即 twentieths of a point为单位。常见换算关系1 英寸 72 点 1440 twips 914400 EMU1 点 20 twips1 厘米 ≈ 567 twips1 厘米 ≈ 28.35 点EMUEnglish Metric Unit用于图片尺寸等更精细的定位1 英寸 914400 EMU。defaultTabStop、hyphenationZone等参数即以此为单位而Document级的背景色则不受此单位体系影响使用十六进制颜色值。仓库 src/util/values.ts 中定义了UniversalMeasure、PositiveUniversalMeasure、Percentage等带单位类型如10.5mm、-5pt、50%供边距、缩进、行距等测量值使用。Compatibility兼容性设置详解兼容性设置是可选配置用于保持早期文字处理软件创建文档的视觉保真度。其中一部分设置提供特定行为如下详述另一部分则是让应用程序模拟既有文字处理软件如 WordPerfect、Word 6.x/95/97的行为const doc new docx.Document({ compatibility: { version: 15, doNotExpandShiftReturn: true, }, });Compatibility Options兼容性选项表以下全部选项都映射到settings.xml的w:compat元素下实现见 src/file/settings/compatibility.tsPropertyTypeNotesPossible ValuesversionnumberOptional15,16,17useSingleBorderforContiguousCellsbooleanOptionaltrue,false,undefinedwordPerfectJustificationbooleanOptionaltrue,false,undefinednoTabStopForHangingIndentbooleanOptionaltrue,false,undefinednoLeadingbooleanOptionaltrue,false,undefinedspaceForUnderlinebooleanOptionaltrue,false,undefinednoColumnBalancebooleanOptionaltrue,false,undefinedbalanceSingleByteDoubleByteWidthbooleanOptionaltrue,false,undefinednoExtraLineSpacingbooleanOptionaltrue,false,undefineddoNotLeaveBackslashAlonebooleanOptionaltrue,false,undefinedunderlineTrailingSpacesbooleanOptionaltrue,false,undefineddoNotExpandShiftReturnbooleanOptionaltrue,false,undefinedspacingInWholePointsbooleanOptionaltrue,false,undefinedlineWrapLikeWord6booleanOptionaltrue,false,undefinedprintBodyTextBeforeHeaderbooleanOptionaltrue,false,undefinedprintColorsBlackbooleanOptionaltrue,false,undefinedspaceWidthbooleanOptionaltrue,false,undefinedshowBreaksInFramesbooleanOptionaltrue,false,undefinedsubFontBySizebooleanOptionaltrue,false,undefinedsuppressBottomSpacingbooleanOptionaltrue,false,undefinedsuppressTopSpacingbooleanOptionaltrue,false,undefinedsuppressSpacingAtTopOfPagebooleanOptionaltrue,false,undefinedsuppressTopSpacingWPbooleanOptionaltrue,false,undefinedsuppressSpBfAfterPgBrkbooleanOptionaltrue,false,undefinedswapBordersFacingPagesbooleanOptionaltrue,false,undefinedconvertMailMergeEscbooleanOptionaltrue,false,undefinedtruncateFontHeightsLikeWP6booleanOptionaltrue,false,undefinedmacWordSmallCapsbooleanOptionaltrue,false,undefinedusePrinterMetricsbooleanOptionaltrue,false,undefineddoNotSuppressParagraphBordersbooleanOptionaltrue,false,undefinedwrapTrailSpacesbooleanOptionaltrue,false,undefinedfootnoteLayoutLikeWW8booleanOptionaltrue,false,undefinedshapeLayoutLikeWW8booleanOptionaltrue,false,undefinedalignTablesRowByRowbooleanOptionaltrue,false,undefinedforgetLastTabAlignmentbooleanOptionaltrue,false,undefinedadjustLineHeightInTablebooleanOptionaltrue,false,undefinedautoSpaceLikeWord95booleanOptionaltrue,false,undefinednoSpaceRaiseLowerbooleanOptionaltrue,false,undefineddoNotUseHTMLParagraphAutoSpacingbooleanOptionaltrue,false,undefinedlayoutRawTableWidthbooleanOptionaltrue,false,undefinedlayoutTableRowsApartbooleanOptionaltrue,false,undefineduseWord97LineBreakRulesbooleanOptionaltrue,false,undefineddoNotBreakWrappedTablesbooleanOptionaltrue,false,undefineddoNotSnapToGridInCellbooleanOptionaltrue,false,undefinedselectFieldWithFirstOrLastCharacterbooleanOptionaltrue,false,undefinedapplyBreakingRulesbooleanOptionaltrue,false,undefineddoNotWrapTextWithPunctuationbooleanOptionaltrue,false,undefineddoNotUseEastAsianBreakRulesbooleanOptionaltrue,false,undefineduseWord2002TableStyleRulesbooleanOptionaltrue,false,undefinedgrowAutofitbooleanOptionaltrue,false,undefineduseFELayoutbooleanOptionaltrue,false,undefineduseNormalStyleForListbooleanOptionaltrue,false,undefineddoNotUseIndentAsNumberingTabStopbooleanOptionaltrue,false,undefineduseAlternateEastAsianLineBreakRulesbooleanOptionaltrue,false,undefinedallowSpaceOfSameStyleInTablebooleanOptionaltrue,false,undefineddoNotSuppressIndentationbooleanOptionaltrue,false,undefineddoNotAutofitConstrainedTablesbooleanOptionaltrue,false,undefinedautofitToFirstFixedWidthCellbooleanOptionaltrue,false,undefinedunderlineTabInNumberingListbooleanOptionaltrue,false,undefineddisplayHangulFixedWidthbooleanOptionaltrue,false,undefinedsplitPgBreakAndParaMarkbooleanOptionaltrue,false,undefineddoNotVerticallyAlignCellWithSpbooleanOptionaltrue,false,undefineddoNotBreakConstrainedForcedTablebooleanOptionaltrue,false,undefinedignoreVerticalAlignmentInTextboxesbooleanOptionaltrue,false,undefineduseAnsiKerningPairsbooleanOptionaltrue,false,undefinedcachedColumnBalancebooleanOptionaltrue,false,undefined常用兼容项的行为说明version设置 Word 兼容模式版本15对应 Word 201316对应 Word 2016/201917对应 Word 2021。源码中通过createCompatibilitySettingsrc/file/settings/compatibility-setting/compatibility-setting.ts写出w:compatSetting w:namecompatibilityMode w:urihttp://schemas.microsoft.com/office/word w:val15/并默认取15useSingleBorderforContiguousCells表格连续单元格冲突时使用简化边框规则w:useSingleBorderforContiguousCellsdoNotExpandShiftReturn不以软换行ShiftEnter结尾的行不做两端对齐w:doNotExpandShiftReturnsuppressSpBfAfterPgBrk分页符后的首行不使用段前间距w:suppressSpBfAfterPgBrkdoNotSnapToGridInCell表格单元格内含对象时不吸附文档网格w:doNotSnapToGridInCelluseAnsiKerningPairs使用字体的 ANSI 字距对w:useAnsiKerningPairs。组合实战一个完整的 Document将以上所有能力组合起来可得到一个带元数据、自定义属性、背景色、特性开关与兼容模式的完整文档import * as fs from fs; import { Document, Packer, Paragraph } from docx; const doc new Document({ creator: Report Bot, lastModifiedBy: Report Bot, title: 2024 年度财务报告, subject: Finance, keywords: report, annual, finance, description: Auto-generated annual financial report, revision: 3, background: { color: FFFFFF, }, customProperties: [ { name: Department, value: Finance }, { name: Approved, value: true }, { name: Version, value: 2.5 }, ], features: { trackRevisions: false, updateFields: true, // 让 TOC 打开时自动刷新 }, compatibility: { version: 16, doNotExpandShiftReturn: true, useSingleBorderforContiguousCells: true, }, sections: [ { properties: { page: { margin: { top: 720, bottom: 720, left: 720, right: 720 }, // twips }, }, children: [new Paragraph(Hello World)], }, ], }); Packer.toBuffer(doc).then((buffer) { fs.writeFileSync(My Document.docx, buffer); });运行后右键文件查看属性即可看到标题、作者、关键词、自定义属性与修订号用 Word 打开则可见背景、兼容模式与字段自动更新均已生效。仓库 demo 目录demo/还提供了50-readme-demo.ts、54-custom-properties.ts、60-track-revisions.ts、1-basic.ts等多个可运行示例以及浏览器端演示 demo/browser-demo.html库同时支持 Node 与浏览器环境。进一步阅读节与页面布局docs/usage/sections.md、docs/usage/page-layout.md样式体系docs/usage/styling-with-js.md、docs/usage/styling-with-xml.md页眉页脚docs/usage/headers-and-footers.md修订跟踪与批注docs/usage/change-tracking.md、docs/usage/comments.md导出打包docs/usage/packers.md快速上手docs/quickstart.md【免费下载链接】docxEasily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.项目地址: https://gitcode.com/GitHub_Trending/do/docx创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考