htmlspanner-ohos
本项目基于HtmlSpanner开发。
简介
htmlspanner-ohos 是 Android HtmlSpanner 的鸿蒙化等价迁移实现,为 OpenHarmony Text 和 StyledString 提供 HTML 和 CSS 解析能力。该库支持将 HTML 内容转换为 StyledString,实现富文本渲染。
效果展示

下载安装
ohpm install @ohos/htmlspanner
OpenHarmony ohpm 环境配置等更多内容,请参考如何安装 OpenHarmony ohpm 包。
约束与限制
兼容性
- DevEco Studio: 6.0.1 Beta1(6.0.1.245SP4), SDK: API12 Release(5.0.0.71), ROM: 5.1.0.120;
权限要求
- 如需加载网络图片,需在
module.json5中添加网络权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
使用示例
基础用法
import { HtmlSpannerText } from '@ohos/htmlspanner'
@Entry
@Component
struct Index {
@State html: string = '<p>Hello <b>World</b>!</p>'
@State css: string = ''
build() {
Column() {
HtmlSpannerText({
html: this.html,
css: this.css
})
}
.width('100%')
.height('100%')
}
}
链接点击处理
import { HtmlSpannerText } from '@ohos/htmlspanner'
@Entry
@Component
struct Index {
@State html: string = '<a href="https://example.com">点击链接</a>'
build() {
Column() {
HtmlSpannerText({
html: this.html,
css: '',
onLinkClick: (href: string) => {
console.info('Link clicked:', href)
// 处理链接点击
}
})
}
.width('100%')
.height('100%')
}
}
自定义标签处理
import { HtmlSpanner, HtmlSpannerText, TableHandlerCompat } from '@ohos/htmlspanner'
@Entry
@Component
struct Index {
@State html: string = '<table><tr><td>Cell</td></tr></table>'
build() {
Column() {
HtmlSpannerText({
html: this.html,
css: '',
onSpannerReady: (spanner: HtmlSpanner) => {
spanner.registerHandler('table', new TableHandlerCompat(spanner))
}
})
}
.width('100%')
.height('100%')
}
}
使用编译选项
import { HtmlSpannerText } from '@ohos/htmlspanner'
@Entry
@Component
struct Index {
@State html: string = '<p> Multiple spaces </p>'
build() {
Column() {
HtmlSpannerText({
html: this.html,
css: '',
spannerOptions: {
stripExtraWhiteSpace: true
}
})
}
.width('100%')
.height('100%')
}
}
使用说明
HtmlSpannerText 组件
HtmlSpannerText 是最常用的组件,直接渲染 HTML 内容。
基本属性:
html: string- HTML 内容css: string- CSS 样式(可选)spannerOptions: Partial<HtmlSpannerOptions>- 编译选项(可选)cancellationCallback: CancellationCallback- 取消回调(可选)onLinkClick: (href: string) => void- 链接点击回调(可选)imageLoader: HtmlSpannerImageLoader- 自定义图片加载器(可选)onSpannerReady: (spanner: HtmlSpanner) => void- Spanner 就绪回调(可选)
HtmlSpanner 类
HtmlSpanner 提供了更底层的 API,适用于需要手动控制渲染流程的场景。
主要方法:
// 创建实例
const spanner = new HtmlSpanner(options?, rendererOptions?)
// 解析 HTML 为节点树
const node = spanner.parse(html, callback?)
// 编译为文本模型
const model = spanner.toModel(html, css?, callback?)
// 渲染为 StyledString
const styledString = spanner.fromHtml(html, css?, callback?)
// 异步渲染(支持异步图片加载)
const styledString = await spanner.fromHtmlAsync(html, css?, callback?)
// 注册自定义标签处理器
spanner.registerHandler(tagName, handler)
// 注销标签处理器
spanner.unregisterHandler(tagName)
CSS 支持
库支持部分 CSS 属性,包括:
- 文本样式:
color,font-size,font-weight,font-style,font-family - 文本装饰:
text-decoration,text-align,text-indent - 布局:
display,margin-*,padding-* - 背景:
background-color - 边框:
border-style,border-color,border-width
图片加载
默认支持以下图片源:
- HTTP/HTTPS URL:
<img src="https://example.com/image.png"> - 应用资源:
<img src="$media:icon">或<img src="app.media.icon"> - 本地文件路径
自定义图片加载:
HtmlSpannerText({
html: this.html,
css: '',
imageLoader: (source: string, run: AttachmentRun) => {
// 自定义图片加载逻辑
return createDefaultImageAttachment(run)
}
})
表格支持
表格处理需要手动注册 TableHandlerCompat:
import { HtmlSpanner, HtmlSpannerText, TableHandlerCompat } from '@ohos/htmlspanner'
HtmlSpannerText({
html: '<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>',
css: '',
onSpannerReady: (spanner: HtmlSpanner) => {
spanner.registerHandler('table', new TableHandlerCompat(spanner))
}
})
取消解析
支持通过 CancellationCallback 取消长时间运行的解析任务:
interface CancelGate {
cancelled: boolean
}
class GateCallback implements CancellationCallback {
private readonly gate: CancelGate
constructor(gate: CancelGate) {
this.gate = gate
}
isCancelled(): boolean {
return this.gate.cancelled
}
}
const gate: CancelGate = { cancelled: false }
const callback = new GateCallback(gate)
HtmlSpannerText({
html: largeHtml,
css: '',
cancellationCallback: callback
})
// 取消解析
gate.cancelled = true
接口说明
组件
| 名称 | 描述 | 主要参数 | 必填 | HarmonyOS 平台支持 |
|---|---|---|---|---|
| HtmlSpannerText | HTML渲染组件,直接将HTML内容渲染为StyledString | html: string // HTML内容 css?: string // CSS样式 spannerOptions?: Partial<HtmlSpannerOptions> // 编译选项 cancellationCallback?: CancellationCallback // 取消回调 imageLoader?: HtmlSpannerImageLoader // 图片加载器 onLinkClick?: (href: string) => void // 链接点击回调 onSpannerReady?: (spanner: HtmlSpanner) => void // Spanner就绪回调 |
是 | 是 |
HtmlSpanner 方法
| 方法名 | 描述 | 参数 | 返回值 | HarmonyOS 平台支持 |
|---|---|---|---|---|
| parse | 解析HTML为节点树 | html: string // HTML内容 callback?: CancellationCallback // 取消回调 |
HtmlSpannerNode | 是 |
| parseUtf8 | 解析UTF-8字节 | bytes: Uint8Array // UTF-8字节数组 callback?: CancellationCallback // 取消回调 |
HtmlSpannerNode | 是 |
| toModel | 编译为文本模型 | html: string // HTML内容 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
SpannerTextModel | 是 |
| toModelUtf8 | 从UTF-8字节编译模型 | bytes: Uint8Array // UTF-8字节数组 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
SpannerTextModel | 是 |
| fromHtml | 渲染为StyledString | html: string // HTML内容 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
StyledString | 是 |
| fromHtmlAsync | 异步渲染为StyledString | html: string // HTML内容 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
Promise<StyledString> | 是 |
| fromHtmlUtf8 | 从UTF-8字节渲染 | bytes: Uint8Array // UTF-8字节数组 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
StyledString | 是 |
| fromTagNode | 从节点树渲染 | root: HtmlSpannerNode // 节点树 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
StyledString | 是 |
| toStyledString | 渲染为StyledString | html: string // HTML内容 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
StyledString | 是 |
| toStyledStringAsync | 异步渲染为StyledString | html: string // HTML内容 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
Promise<StyledString> | 是 |
| toMutableStyledString | 渲染为MutableStyledString | html: string // HTML内容 css?: string // CSS样式 callback?: CancellationCallback // 取消回调 |
MutableStyledString | 是 |
| registerHandler | 注册标签处理器 | tagName: string // 标签名 handler: TagNodeHandlerCompat // 处理器 |
void | 是 |
| unregisterHandler | 注销标签处理器 | tagName: string // 标签名 | void | 是 |
| getHandlerFor | 获取标签处理器 | tagName: string // 标签名 | TagNodeHandlerCompat | undefined | 是 |
| getFont | 获取字体 | name: string | undefined // 字体名 | FontFamily | 是 |
| setFontResolver | 设置字体解析器 | resolver: FontResolver // 字体解析器 | void | 是 |
| setStripExtraWhiteSpace | 设置空白折叠 | value: boolean // 是否折叠空白 | void | 是 |
| setAllowStyling | 设置是否允许样式 | value: boolean // 是否允许样式 | void | 是 |
| setUseColoursFromStyle | 设置是否使用样式颜色 | value: boolean // 是否使用样式颜色 | void | 是 |
| setUseFontSizeFromStyle | 设置是否使用样式字号 | value: boolean // 是否使用样式字号 | void | 是 |
类型
| 名称 | 描述 | 字段 | HarmonyOS 平台支持 |
|---|---|---|---|
| HtmlSpannerOptions | HtmlSpanner构造选项 | stripExtraWhiteSpace?: boolean // 是否折叠空白 allowStyling?: boolean // 是否允许样式 useColoursFromStyle?: boolean // 是否使用样式颜色 useFontSizeFromStyle?: boolean // 是否使用样式字号 pruneTags?: string[] // 剪枝标签列表 fontResolver?: FontResolver // 字体解析器 contrastPatcher?: ContrastPatcher // 对比度补丁器 htmlCleaner?: HtmlSpannerHtmlCleaner // HTML清理器 |
是 |
| StyledStringRendererOptions | StyledStringRenderer渲染选项 | - | 是 |
| CancellationCallback | 取消回调接口 | isCancelled: () => boolean // 返回是否已取消 | 是 |
| HtmlSpannerImageLoader | 图片加载器类型 | source: string // 图片源 run: AttachmentRun // 附件运行信息 |
是 |
| HtmlSpannerImageLoaderResult | 图片加载器返回类型 | ImageAttachment | Promise<ImageAttachment | undefined> | undefined | 是 |
| AttachmentRun | 附件运行信息 | 包含图片的位置、尺寸等 | 是 |
| LinkRun | 链接运行信息 | - | 是 |
| CustomRun | 自定义运行信息 | - | 是 |
| CustomRunData | 自定义运行数据 | - | 是 |
| SerializableStyleRun | 可序列化样式运行 | - | 是 |
| TableRowAttachmentPayload | 表格行附件负载 | - | 是 |
| StyleProperties | 样式属性接口 | - | 是 |
| StyleValueUnit | 样式值单位 | 'px' | 'em' | 'percentage' | 'pt' | 'rem' | 'vw' | 'vh' | 'auto' | 是 |
| TableRasterLayoutSpec | 表格格栅布局规格 | - | 是 |
| TableCellRect | 表格单元格矩形 | - | 是 |
| TableComplianceLayoutOptions | 表格合规布局选项 | - | 是 |
| HtmlSpannerTextCustomTagRule | 自定义标签规则 | tagName: string // 标签名 style?: HtmlSpannerTextCustomTagStyle // 样式 display?: HtmlSpannerTextCustomTagDisplay // 显示类型 |
是 |
| HtmlSpannerTextCustomTagStyle | 自定义标签样式 | fontFamily?: string // 字体族 fontSize?: number // 字号 fontWeight?: HtmlSpannerTextCustomTagFontWeight // 字重 fontStyle?: HtmlSpannerTextCustomTagFontStyle // 字体样式 color?: string // 颜色 backgroundColor?: string // 背景色 textDecoration?: HtmlSpannerTextCustomTagTextDecoration // 文本装饰 textAlign?: HtmlSpannerTextCustomTagTextAlign // 文本对齐 |
是 |
| HtmlSpannerTextCustomTagDisplay | 自定义标签显示类型 | 'inline' | 'block' | 是 |
| HtmlSpannerTextCustomTagFontWeight | 自定义标签字重 | number | 'normal' | 'bold' | 是 |
| HtmlSpannerTextCustomTagFontStyle | 自定义标签字体样式 | 'normal' | 'italic' | 是 |
| HtmlSpannerTextCustomTagTextAlign | 自定义标签文本对齐 | 'left' | 'center' | 'right' | 'justify' | 是 |
| HtmlSpannerTextCustomTagTextDecoration | 自定义标签文本装饰 | 'none' | 'underline' | 'line-through' | 'overline' | 是 |
| FontTypeface | 字体字重 | fontFamily: string // 字体族名 fontWeight?: number // 字重 |
是 |
| HttpImageLayoutSnapshotVp | HTTP图片布局快照 | - | 是 |
| ScaledHttpImageDecodeDebugInfo | 缩放图片解码调试信息 | - | 是 |
| HttpImageCenterDebugLogger | HTTP图片居中调试日志器 | - | 是 |
| HtmlSpannerFileSource | 文件源 | - | 是 |
| HtmlSpannerHtmlSource | HTML源 | - | 是 |
| HtmlSpannerLoaderSource | 加载器源 | - | 是 |
| HtmlSpannerRawFileSource | 原始文件源 | - | 是 |
| HtmlSpannerTextSource | 文本源 | - | 是 |
| HtmlSpannerUtf8Source | UTF-8源 | - | 是 |
| SpannerTextModelJson | 文本模型JSON | - | 是 |
| CssDeclarationCompat | CSS声明 | - | 是 |
| CssRuleCompat | CSS规则 | - | 是 |
| CompiledCssRuleCompat | 编译后CSS规则 | - | 是 |
| StyleUpdater | 样式更新器 | - | 是 |
| StyleUpdaterHost | 样式更新器宿主 | - | 是 |
| TagNodeMatcher | 标签节点匹配器 | - | 是 |
函数
| 名称 | 描述 | 参数 | 返回值 | HarmonyOS 平台支持 |
|---|---|---|---|---|
| createDefaultImageAttachment | 创建默认图片附件 | run: AttachmentRun // 附件运行信息 | ImageAttachment | undefined | 是 |
| createImageCacheKey | 创建图片缓存键 | run: AttachmentRun // 附件运行信息 | string | 是 |
| createImagePlaceholder | 创建图片占位符 | run: AttachmentRun // 附件运行信息 failed: boolean // 是否加载失败 |
StyledString | 是 |
| createScaledHttpImageLoader | 创建HTTP图片加载器 | - | HtmlSpannerImageLoader | 是 |
| createScaledHttpImageAttachment | 创建缩放HTTP图片附件 | run: AttachmentRun // 附件运行信息 displayDensity: number // 显示密度 |
ImageAttachment | undefined | 是 |
| createScaledHttpImageAttachmentResolver | 创建缩放HTTP图片附件解析器 | displayDensity: number // 显示密度 | (run: AttachmentRun) => ImageAttachment | undefined | 是 |
| clearHttpImageLayoutCache | 清除HTTP图片布局缓存 | - | void | 是 |
| computeParagraphCenterLineBoxWidthVp | 计算段落居中行盒宽度 | - | number | 是 |
| expandHttpImageForParagraphCenterFromCache | 从缓存扩展HTTP图片 | run: AttachmentRun // 附件运行信息 | ImageAttachment | undefined | 是 |
| getHttpImageLayoutSnapshotDimensions | 获取HTTP图片布局快照尺寸 | run: AttachmentRun // 附件运行信息 | HttpImageLayoutSnapshotVp | undefined | 是 |
| parseStyleValue | 解析样式值 | input: string | undefined | null // 样式字符串 | StyleValue | undefined | 是 |
| translateLegacyFontSize | 转换传统字号(1-7) | fontSize: number // 传统字号(1-7) | StyleValue | 是 |
| decodeUtf8BytesToString | UTF-8字节解码为字符串 | bytes: Uint8Array // UTF-8字节数组 | string | 是 |
| replaceHtmlEntities | 替换HTML实体 | text: string // 文本内容 inAttribute: boolean // 是否在属性中 |
string | 是 |
| createDefaultContrastPatcher | 创建默认对比度补丁器 | - | ContrastPatcher | 是 |
| defaultHtmlSpannerOptions | 获取默认选项 | - | HtmlSpannerOptions | 是 |
| mergeHtmlSpannerOptions | 合并选项 | options?: Partial<HtmlSpannerOptions> // 部分选项 | HtmlSpannerOptions | 是 |
| defaultStyledStringRendererOptions | 获取默认渲染器选项 | - | StyledStringRendererOptions | 是 |
| readHtmlSource | 读取HTML源 | source: HtmlSpannerHtmlSource // HTML源 | string | Promise<string> | 是 |
| getDisplayDensity | 获取显示密度 | - | number | 是 |
| buildTableRasterLayoutSpecFromAttachmentRun | 构建表格格栅布局规格 | run: AttachmentRun // 附件运行信息 | TableRasterLayoutSpec | undefined | 是 |
| createTableComplianceAttachmentResolver | 创建表格合规附件解析器 | options?: TableComplianceLayoutOptions // 布局选项 | (run: AttachmentRun) => ImageAttachment | undefined | 是 |
| rasterTableLayoutSpecWithOffscreenCanvas | 离屏Canvas栅格化表格 | spec: TableRasterLayoutSpec // 布局规格 | ImageAttachment | 是 |
| compileCssRulesSkippingFailures | 编译CSS规则跳过失败 | rules: string[] // CSS规则数组 | CompiledCssRuleCompat[] | 是 |
| createMatchersFromSelector | 从选择器创建匹配器 | selector: string // CSS选择器 | TagNodeMatcher[] | 是 |
| matchesSelectorChain | 匹配选择器链 | node: HtmlSpannerNode // HTML节点 matchers: TagNodeMatcher[] // 匹配器数组 |
boolean | 是 |
关于混淆
在 obfuscation-rules.txt 中添加以下规则以避免混淆:
-keep class @ohos/htmlspanner.** { *; }
-keep class * implements @ohos/htmlspanner.HtmlSpannerImageLoader { *; }
-keep class * implements @ohos/htmlspanner.FontResolver { *; }
-keep class * implements @ohos/htmlspanner.CancellationCallback { *; }
目录结构
htmlspanner-ohos/
├── library/ # 核心库代码
│ ├── src/main/ets/
│ │ ├── components/ # 组件(HtmlSpannerText)
│ │ ├── font/ # 字体处理
│ │ ├── handler/ # 标签处理器
│ │ ├── htmlspanner/ # 核心类
│ │ ├── model/ # 数据模型
│ │ ├── parser/ # 解析器
│ │ ├── renderer/ # 渲染器
│ │ ├── style/ # 样式处理
│ │ ├── table/ # 表格处理
│ │ └── util/ # 工具函数
│ └── oh-package.json5 # 库配置
├── entry/ # Demo 应用
├── docs/ # 文档
├── tests/ # 测试用例
├── scripts/ # 构建脚本
├── LICENSE # 许可证
├── NOTICE # 版权声明
└── README.OpenSource # 开源声明
开源协议
本项目基于 Apache License 2.0 许可证。
第三方依赖
- @ohos/htmlparser2 - HTML 解析器
- @ohos/postcss - CSS 处理器