
说明
将 Google Docs 文档的 JSON 代表转换为 HTML 抽象语法树( HAST) 它可以被序列化为HTML,也可以被转换为Markdown.
说明: 这个图书馆的确是 没有 打算与Google Docs的渲染相匹配.
安装
利用国家预防机制或类似机制安装.
npm i @googleworkspace/google-docs-hast
使用量
import { toHast } from "@googleworkspace/google-docs-hast";
// Retrieve document from API, https://developers.google.com/docs/api
const doc = ...;
// Convert the document to an HTML AST.
const tree = toHast(doc);
为了获得HTML AST的序列化代表,请使用 重排字符串 软件包.
import { unified } from "unified";
import rehypeStringify from "rehype-stringify";
// Convert the document to an HTML string.
const html = unified()
.use(rehypeStringify, { collapseEmptyAttributes: true })
.stringify(tree);
图像
全体 <img> 各项内容应作为 src 属性只在短时间内有效,并且属于模式 https://lh6.googleusercontent.com/...。 。 。 .
import { visit } from "unist-util-visit";
visit(tree, (node) => {
if (node.type === "element" && node.tagName === "img") {
const { src } = node.properties;
// download, store, and replace the src attribute
node.properties.src = newSrc;
}
});
命名样式
命名样式转换为匹配下表的 HTML 元素.
| 命名样式 | HTML 语言 |
|---|---|
| 标题 | <h1 class="title"></h1> |
| 字幕 | <p class="subtitle"></p> |
| 标题1 | <h1 class="heading-1"></h1> |
| 标题2 | <h2 class="heading-2"></h2> |
| 标题3 | <h3 class="heading-3"></h3> |
| 标题4 | <h4 class="heading-4"></h4> |
| 标题5 | <h5 class="heading-5"></h5> |
| 标题6 | <h6 class="heading-6"></h6> |
| 普通文本 | <p class="normal-text"></p> |
文本样式
文本样式转换为 HTML 元素 : <i>, (中文(简体) ), <strong>, (中文(简体) ), <s>, (中文(简体) ), <sub>, (中文(简体) ), <sup>,以及 <u>。 。 。 .
如果没有直接绘图,a <span> cSS用于支持文本颜色和字体等特性. 此选项可禁用 { styles: false }。 。 。 .
锁定链接
标题标识在表格中 id="h.wn8l66qm9m7y" 当从 Google Docs API 导出时。 默认情况下,会更新标题标记ID,以匹配其文本内容. 见 滑轮 关于如何做到这一点的更多信息.
例如,以下html:
<h1 class="heading-1" id="h.wn8l66qm9m7y">A heading</h1>
改为:
<h1 class="heading-1" id="a-heading">A heading</h1>
此选项可禁用 { prettyHeaderIds: false}。 。 。 .
const tree = toHast(doc, { prettyHeaderIds: false });
不支持的特性
Google Docs的一些功能目前不为这个库所支持. 这份清单并非详尽无遗.
| 类型 | 支助 | 错误 |
|---|---|---|
| 适用于嵌入对象的样式,包括边框、旋转、透明度 | ❌ | |
documentStyle 包括页码、边距等 | ❌ | |
namedStyles (仅作为类名添加在相应的标签上) | ❌ | |
| 页码 | ❌ | |
| 分页符 | ❌ | |
| 方程式 | ❌ | |
| 列数 | ❌ | |
| 建议 | ❌ | |
| 书签 | ❌ |
说明: 这个图书馆的确是 没有 打算与Google Docs的渲染相匹配.
这不是Google的官方产品.