
现代开发团队经常需要与不使用代码编辑器的项目经理、客户、审计人员或教育工作者分享 JavaScript 或 JSX 源代码。然而,原始的 .js 和 .jsx 文件在 VS Code 或 WebStorm 等工具之外难以查看,而手动将代码复制到 Word 文档中经常会破坏缩进、格式和可读性。
通过将 Spire.Doc for Python 与 Pygments 结合使用,开发人员可以在 Python 中将 JavaScript 转换为 Word,并实现语法高亮和可自定义的文档格式。这种自动化方法适用于技术文档、合规归档、教育材料、代码审查和客户交付物。
本文将介绍如何使用 Spire.Doc for Python 在 Python 中将 JavaScript 和 JSX 文件转换为 Word 文档,包括基本转换、高级格式化技术、批量处理和 PDF 导出。
快速导航
1. 理解转换工作流程
转换过程使用 Pygments 生成带语法高亮的 HTML,然后使用 Spire.Doc 的 HTML 导入功能将此 HTML 导入到 Word 文档中:
- 从
.js或.jsx文件读取源代码 - 使用 Pygments 的
highlight()函数生成带语法高亮的 HTML - 使用
AppendHTML()将 HTML 导入到 Word 中
这种方法通过 Pygments 的内置样式提供语法着色,同时 Spire.Doc 处理文档结构,包括页边距、页眉、页脚和多格式导出。它为自动化转换过程提供了简单灵活的 API。
2. 前置条件
在 Python 中将 JavaScript 文件转换为 Word 文档之前,需要安装 Spire.Doc for Python 和 Pygments:
pip install spire.doc
pip install pygments
验证包是否可用:
import spire.doc
from pygments import highlight
from pygments.formatters import HtmlFormatter
或者,可以下载 Spire.Doc for Python 并将其添加到项目中。
3. 基本实现
以下示例将 JavaScript 文件转换为带有语法高亮的 Word 文档:
from spire.doc import *
from pygments import highlight
from pygments.lexers import JavascriptLexer
from pygments.formatters import HtmlFormatter
def convert_js_to_word(input_file: str, output_file: str) -> None:
"""将 JavaScript 文件转换为带有语法高亮的 Word 文档。"""
with open(input_file, "r", encoding="utf-8") as file:
js_code = file.read()
document = Document()
section = document.AddSection()
section.PageSetup.Margins.All = 50
title_paragraph = section.AddParagraph()
title_text = title_paragraph.AppendText(f"源代码:{input_file}")
title_text.CharacterFormat.FontName = "微软雅黑"
title_text.CharacterFormat.FontSize = 14
title_text.CharacterFormat.Bold = True
title_paragraph.Format.AfterSpacing = 10
html_formatter = HtmlFormatter(
nowrap=True,
style='colorful',
noclasses=True
)
highlighted_html = highlight(js_code, JavascriptLexer(), html_formatter)
code_paragraph = section.AddParagraph()
code_paragraph.AppendHTML(f'<pre style="font-family: Consolas; font-size: 10pt;">{highlighted_html}</pre>')
document.SaveToFile(output_file, FileFormat.Docx)
document.Close()
print(f"已将 {input_file} 转换为 {output_file}")
convert_js_to_word("app.js", "JavaScriptCode.docx")

关键组件
- Document – Word 文档容器,用于存放节、段落和内容
- Section – 具有页面设置属性(页边距、方向)的文档节
- Paragraph – 具有格式选项的文本容器
- AppendHTML() – 将 HTML 内容导入到段落中,包括用于颜色和字体的内联样式
- highlight() – Pygments 函数,生成语法高亮输出
- HtmlFormatter – Pygments 格式化器,生成带有内联样式的 HTML(使用
noclasses=True) - JavascriptLexer – Pygments 词法分析器,识别 JavaScript 语法元素
Spire.Doc 可以导入由 Pygments 生成的带语法高亮的 HTML,使 JavaScript 代码格式和颜色能够在 Word 文档中保留。
4. 高级应用场景
转换 JSX 文件
对于 JSX 文件,建议使用 JsxLexer 而不是 JavascriptLexer,以实现对组件标签和嵌入式 JSX 表达式更准确的语法高亮。
JSX 输入示例(App.jsx):
import React, { useState } from 'react';
const TodoList = () => {
const [todos, setTodos] = useState([]);
return (
<div className="todo-container">
<h1>我的任务</h1>
</div>
);
};
export default TodoList;
在生成带语法高亮的 HTML 时使用 JsxLexer:
from pygments.lexers import JsxLexer
highlighted_html = highlight(
jsx_code,
JsxLexer(),
html_formatter
)
然后使用相同的 AppendHTML() 工作流将高亮的 JSX 内容转换为 Word:
convert_js_to_word("App.jsx", "ReactComponent.docx")
转换结果如下所示:

与标准 JavaScript 词法分析器相比,JsxLexer 对 JSX 标签、属性和嵌入式表达式的识别能力更强,从而在生成的 Word 文档中实现更准确的语法着色。
批量转换多个文件
如果需要转换大量 JavaScript 或 JSX 文件,可以通过扫描文件夹并批量生成 Word 文档来自动化此过程。
import os
from pathlib import Path
def batch_convert_js_files(source_folder: str, output_folder: str) -> None:
"""将文件夹中的所有 JavaScript 文件转换为 Word 文档。"""
Path(output_folder).mkdir(parents=True, exist_ok=True)
js_extensions = ('.js', '.jsx', '.mjs')
converted_count = 0
error_count = 0
for filename in os.listdir(source_folder):
if filename.lower().endswith(js_extensions):
input_path = os.path.join(source_folder, filename)
base_name = os.path.splitext(filename)[0]
output_path = os.path.join(output_folder, f"{base_name}.docx")
try:
convert_js_to_word(input_path, output_path)
converted_count += 1
except Exception as e:
print(f"转换 {filename} 时出错:{str(e)}")
error_count += 1
print(f"\n批量转换完成:")
print(f" 已转换:{converted_count} 个文件")
print(f" 错误:{error_count} 个文件")
batch_convert_js_files("src/scripts", "output/docs")
添加行号
行号可以提高代码审查、审计或技术文档期间的可读性。由于 Word HTML 渲染可能不完全支持 Pygments 的内置行号布局,一种实用的方法是在语法高亮后 prepending 自定义行号。
html_formatter = HtmlFormatter(
nowrap=True,
noclasses=True,
style="colorful"
)
highlighted_html = highlight(
js_code,
JavascriptLexer(),
html_formatter
)
highlighted_lines = highlighted_html.splitlines()
numbered_lines = []
for index, line in enumerate(highlighted_lines, start=1):
numbered_line = (
f'<span style="color: gray; font-weight: bold;">'
f'{index:4d} '
f'</span>{line}'
)
numbered_lines.append(numbered_line)
combined_html = (
'<pre style="font-family: Consolas; '
'font-size: 10pt; line-height: 1.4;">'
+ '\n'.join(numbered_lines) +
'</pre>'
)
paragraph.AppendHTML(combined_html)
生成的带行号的 Word 文档如下所示:

添加页眉和页脚
页眉和页脚通过添加标题、页码和文档元数据来帮助组织生成的 Word 文档。这对于正式报告或导出的技术文档特别有用。
def add_document_metadata(section: Section, document_title: str) -> None:
"""向文档节添加页眉和页脚。"""
header = section.HeadersFooters.Header.AddParagraph()
header_text = header.AppendText(document_title)
header_text.CharacterFormat.FontName = "微软雅黑"
header_text.CharacterFormat.FontSize = 10
header_text.CharacterFormat.TextColor = Color.get_Black()
header.Format.HorizontalAlignment = HorizontalAlignment.Left
header.Format.TextAlignment = TextAlignment.Top
header.Format.Borders.Bottom.BorderType = BorderStyle.Single
header.Format.Borders.Bottom.Color = Color.get_Black()
footer = section.HeadersFooters.Footer.AddParagraph()
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
footer.Format.TextAlignment = TextAlignment.Bottom
page_field = footer.AppendField("page", FieldType.FieldPage)
page_field.CharacterFormat.FontName = "微软雅黑"
page_field.CharacterFormat.FontSize = 9
footer.AppendText(" / ")
total_pages_field = footer.AppendField("numPages", FieldType.FieldNumPages)
total_pages_field.CharacterFormat.FontName = "微软雅黑"
total_pages_field.CharacterFormat.FontSize = 9
document = Document()
document.LoadFromFile("CodeWithLines.docx")
section = document.Sections[0]
add_document_metadata(section, "JavaScript 源代码文档")
document.SaveToFile("CodeWithHeadersFooters.docx", FileFormat.Docx)
生成的带页眉和页脚的 Word 文档如下所示:

有关更多高级自定义选项,请参阅关于如何在 Python 中向 Word 文档添加页眉和页脚的指南。
导出为 PDF 格式
除了 DOCX 输出外,Spire.Doc 还可以将带语法高亮的 JavaScript 代码直接导出为 PDF 格式。这在分发只读文档或在 Microsoft Word 环境之外共享代码时非常有用。
def convert_js_to_pdf(input_file: str, output_file: str) -> None:
"""将 JavaScript 文件直接转换为 PDF。"""
with open(input_file, "r", encoding="utf-8") as file:
js_code = file.read()
document = Document()
section = document.AddSection()
section.PageSetup.Margins.All = 50
html_formatter = HtmlFormatter(noclasses=True, style='colorful')
highlighted_html = highlight(js_code, JavascriptLexer(), html_formatter)
paragraph = section.AddParagraph()
paragraph.AppendHTML(f'<pre style="font-family: Consolas; font-size: 10pt;">{highlighted_html}</pre>')
document.SaveToFile(output_file, FileFormat.PDF)
document.Close()
convert_js_to_pdf("app.js", "JavaScriptCode.pdf")
有关更多高级 PDF 转换技术,包括布局控制和文档格式,请参阅关于在 Python 中将 Word 文档转换为 PDF的详细指南。
自定义语法高亮样式
Pygments 提供多种内置配色方案:
def convert_with_custom_style(input_file: str, output_file: str, style_name: str = 'monokai') -> None:
"""使用自定义高亮样式将 JavaScript 转换为 Word。"""
with open(input_file, "r", encoding="utf-8") as file:
js_code = file.read()
document = Document()
section = document.AddSection()
section.PageSetup.Margins.All = 50
html_formatter = HtmlFormatter(
noclasses=True,
style=style_name,
nowrap=True
)
highlighted_html = highlight(js_code, JavascriptLexer(), html_formatter)
paragraph = section.AddParagraph()
paragraph.AppendHTML(f'<pre style="font-family: Consolas; font-size: 10pt;">{highlighted_html}</pre>')
document.SaveToFile(output_file, FileFormat.Docx)
document.Close()
convert_with_custom_style("app.js", "CodeMonokai.docx", style_name='monokai')
可用样式包括:'monokai'、'colorful'、'vim'、'vs'、'tango'、'friendly'、'default'
5. 常见陷阱
缺少 HtmlFormatter 配置
问题: 默认的 HtmlFormatter 生成 CSS 类而不是内联样式,如果没有外部样式表,Word 无法处理。
解决方案: 始终使用 noclasses=True:
html_formatter = HtmlFormatter(noclasses=True, style='colorful')
highlighted_html = highlight(js_code, JavascriptLexer(), html_formatter)
特殊字符的编码错误
问题: 在不指定 UTF-8 编码的情况下读取文件会导致某些平台上的字符损坏。
解决方案: 显式指定 UTF-8 编码:
with open(input_file, "r", encoding="utf-8") as file:
js_code = file.read()
对于带有 BOM(字节顺序标记)的文件,使用 utf-8-sig:
with open(input_file, "r", encoding="utf-8-sig") as file:
js_code = file.read()
缩进丢失
问题: 未将高亮代码包装在 <pre> 标签中会导致缩进消失。
解决方案: 将语法高亮的 HTML 包装在 <pre> 标签中:
highlighted_html = highlight(js_code, JavascriptLexer(), html_formatter)
paragraph.AppendHTML(f'<pre style="font-family: Consolas;">{highlighted_html}</pre>')
ModuleNotFoundError
问题: 当前 Python 环境中未安装包。
解决方案:
pip install spire.doc
对于虚拟环境,在安装前确保激活:
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
pip install spire.doc
大文件的性能问题
问题: 非常大的 JavaScript 文件(10,000+ 行)可能导致转换缓慢。
解决方案: 分块处理文件:
def convert_large_file(input_file: str, output_file: str, chunk_size: int = 500) -> None:
"""分块转换大型 JavaScript 文件。"""
with open(input_file, "r", encoding="utf-8") as file:
lines = file.readlines()
document = Document()
section = document.AddSection()
section.PageSetup.Margins.All = 50
html_formatter = HtmlFormatter(noclasses=True, style='colorful')
for i in range(0, len(lines), chunk_size):
chunk = ''.join(lines[i:i + chunk_size])
highlighted_html = highlight(chunk, JavascriptLexer(), html_formatter)
paragraph = section.AddParagraph()
paragraph.AppendHTML(f'<pre style="font-family: Consolas; font-size: 10pt;">{highlighted_html}</pre>')
document.SaveToFile(output_file, FileFormat.Docx)
document.Close()
总结
本文演示了如何使用 Spire.Doc for Python 和 Pygments 在 Python 中将 JavaScript 和 JSX 文件转换为 Word 文档。通过利用带有 HtmlFormatter 的 highlight() 函数和 Spire.Doc 的 AppendHTML() 方法,开发人员可以使用语法高亮自动化代码文档工作流。
Spire.Doc for Python 提供文档生成功能,包括表格创建、图像插入、页眉/页脚管理和多格式导出。
可以申请30 天免费许可证来评估所有功能。
7. 常见问题
Spire.Doc 可以将 JSX 文件转换为 Word 文档吗?
可以。Pygments 可以使用 JavaScript 词法分析器高亮显示许多 JSX 构造,包括组件标签、props 和嵌入式表达式。但是,JSX 特定语法可能不会获得专用的高亮类别。
此解决方案是否需要安装 Microsoft Word?
不需要。Spire.Doc for Python 独立运行,无需 Microsoft Word。该库直接生成 DOCX 文件,使其适用于服务器环境和 CI/CD 管道。
我可以将 JavaScript 转换为 DOCX 以外的格式吗?
可以。Spire.Doc 支持多种导出格式:
document.SaveToFile("output.pdf", FileFormat.PDF)
document.SaveToFile("output.html", FileFormat.Html)
document.SaveToFile("output.rtf", FileFormat.Rtf)
如何处理 TypeScript 文件(.ts、.tsx)?
使用 TypescriptLexer:
from pygments.lexers import TypescriptLexer
highlighted_html = highlight(ts_code, TypescriptLexer(), html_formatter)
这种方法适合企业级项目吗?
适合。Python 自动化可以与 CI/CD 管道和批处理工作流集成。本地执行避免了将源代码上传到在线转换器的安全风险。对于大型部署,考虑实施日志记录、进度报告和错误跟踪。
可以自定义语法高亮颜色吗?
可以。Pygments 提供众多内置样式:
html_formatter = HtmlFormatter(noclasses=True, style='monokai')
可用样式:'monokai'、'colorful'、'vim'、'vs'、'tango'、'friendly'、'default'







