This module provides the book parsing capability, with support for TXT, EPUB, MOBI, AZW, and AZW3 file formats. BookParserHandler is initialized for the book file that has been imported to the app sandbox directory. With the parsing capability, the basic book information, spine item list, catalog item list, and chapter content can be obtained.
Since: 5.0.4(16)
Basic book information.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| bookTitle | string | No | No | Book title. |
| bookCreator | string | No | Yes | Author. |
| bookPublishDate | string | No | Yes | Publication date. (This parameter is reserved.) |
| bookLanguage | string | No | Yes | Book language. zh_HK: traditional Chinese, including traditional Chinese (Taiwan, China) and traditional Chinese (Hong Kong, China) zh_CN: simplified Chinese zh: Chinese (zh is used as the default value for unsupported or invalid languages.) en_US: English |
| bookCoverImage | string | No | Yes | Path of a book cover image. Example: OEBPS/images/coverpage.jpg. |
| bookCharset | string | No | Yes | Character set of the book content, which is determined by the book encoding format, for example, utf-8. For details about the supported formats, see the TextEncoder definition. (This parameter is reserved.) |
| bookType | string | No | Yes | Book format, which can be txt, epub, mobi, azw, or azw3. |
| isRtl | boolean | No | Yes | Indicates whether the text direction is right-to-left (RTL). (This parameter is reserved.) true: RTL false: left-to-right (LTR) |
| renditionLayout | string | No | Yes | Book layout. (This parameter is reserved.) reflowable: reflowable layout pre-paginated: fixed layout |
| renditionOrientation | string | No | Yes | Orientation. (This parameter is reserved.) landscape portrait auto: auto-adaptive |
| renditionSpread | string | No | Yes | Scenario for merging the left and right pages of the spine. (This parameter is reserved.) none: The left and right pages of the spine are not merged. landscape: The left and right pages of the spine are merged in landscape orientation. portrait: The left and right pages of the spine are merged in portrait orientation. auto: Spine page merging is auto-adaptive. |
Spine item, which identifies a readable content resource, for example, chapter1.xhtml.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| idRef | string | No | No | Content resource ID, which uniquely identifies a body content file. |
| index | number | No | No | Content resource index, starting from 0. |
| href | string | No | No | Reference path of a content resource in a book. Example: /OEBPS/Txt/chapter01.xhtml. |
| properties | string | No | No | Content display mode for two-page view. (This parameter is reserved.) page-spread-left: Content is displayed on the left of the screen. page-spread-right: Content is displayed on the right of the screen. |
Book catalog item, which can be used for displaying the catalog.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| catalogId | number | No | No | Catalog item ID, starting from 0. |
| catalogName | string | No | No | Catalog item name. |
| catalogLevel | number | No | Yes | Catalog item level. For example, the catalog level of Chapter 1 is 0. If there are subchapters below it, the catalog level of the subchapters is incremented by 1, resulting in 1. If there are further subchapters below those subchapters, the level continues to be incremented by 1, resulting in 2. You can identify the hierarchical relationships between catalog items based on the order and level. |
| playOrder | number | No | Yes | Catalog item reading order, starting from 0. (This parameter is reserved.) |
| idRef | string | No | Yes | ID of the content resource corresponding to a catalog item. (This parameter is reserved.) |
| href | string | No | Yes | Content resource path of a catalog item, with an anchor. |
| resourceFile | string | No | Yes | Content resource path of a catalog item, without an anchor. Take an EPUB book as an example. This parameter indicates the relative path of a resource in the root directory /OEBPS. |
A CatalogItem value specifies a catalog item, and a SpineItem value specifies a content resource file. The two items are not necessarily in a one-to-one mapping. For example, if a chapter in an EPUB book has three subchapters, there are four catalog items. However, the four catalog items may map only one content resource file specified by SpineItem based on CatalogItem.resourceFile and SpineItem.href.
type CallbackRes<T, V> = (data: T) => V
Callback API for requesting book resources, which is called when the typesetting engine renders the UI. This API must be used together with the registration API on('resourceRequest') of ReaderComponentController. If there are custom background and font resources, these resources need to be returned through this API.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| data | T | Yes | Parameter of the resource request API. For example, when the API obtains a custom font, this parameter indicates the name of the font to be obtained. |
Returns
| Type | Description |
|---|---|
| V | Return value type of the resource request API. For example, when the API obtains a custom font, the return value indicates the binary data stream of the font file. |
Example:
import { bookParser, readerCore, ReadPageComponent } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Reader {
private readerComponentController: readerCore.ReaderComponentController = new readerCore.ReaderComponentController();
private selectFontPath = 'fonts/SourceHanSerifCN-VF.ttf';
aboutToAppear(): void {
this.registerListener();
}
private async registerListener() {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
await this.readerComponentController.init(context);
this.readerComponentController.on('resourceRequest', this.resourceRequest);
}
private resourceRequest: bookParser.CallbackRes<string, ArrayBuffer> = (fileName: string): ArrayBuffer => {
if (this.isFont(fileName)) {
let res = $rawfile(this.selectFontPath);
let context = this.getUIContext().getHostContext();
if (res && context) {
// Obtain the font data in the resource path.
let value: Uint8Array = context.resourceManager.getRawFileContentSync(this.selectFontPath);
hilog.info(0x0000, 'testTag', 'resourceRequest : get success');
return value.buffer as ArrayBuffer;
}
}
return new ArrayBuffer(0);
}
private isFont(filePath: string): boolean {
let options = ['.ttf', '.woff2', '.otf'];
let path = filePath.toLowerCase();
let result = path.indexOf(options[0]) != -1 || path.indexOf(options[1]) != -1 || path.indexOf(options[2]) != -1;
hilog.info(0x0000, 'testTag', 'isFont = ' + result);
return result;
}
build() {
Stack() {
ReadPageComponent({
controller: this.readerComponentController,
readerCallback: (err: BusinessError, data: readerCore.ReaderComponentController) => {
this.readerComponentController = data;
}
})
}.width('100%').height('100%')
}
} getDefaultHandler(path: string): Promise<BookParserHandler>
Obtains the default book parser. This API returns the result asynchronously through a promise.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| path | string | Yes | Local book file path. Only the app sandbox directory of the current app is supported. |
Returns
| Type | Description |
|---|---|
| Promise<BookParserHandler> | Promise used to return the BookParserHandler class. |
Error codes
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1017000999 | Other error. |
| 1017010003 | Book file format is unexpected. |
| 1017010004 | File is not exist. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.initBookParser();
}
private async initBookParser() {
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
// Call the bookParserHandler API based on your service needs.
hilog.info(0x0000, 'testTag', `getDefaultHandler succeeded`);
}
build() {
// Implement the page layout based on your service needs.
}
} Book parsing API class.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
getBookInfo(): BookInfo
Obtains book information.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Returns
| Type | Description |
|---|---|
| BookInfo | Basic book information. |
Error codes
| ID | Error Message |
|---|---|
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010002 | Invalid request. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getBookInfo();
}
private async getBookInfo() {
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
let bookInfo: bookParser.BookInfo = bookParserHandler.getBookInfo();
hilog.info(0x0000, 'testTag', `getBookInfo succeeded, bookInfo:` + JSON.stringify(bookInfo));
}
build() {
// Implement the page layout based on your service needs.
}
} getCatalogList(): CatalogItem[]
Obtains the catalog item list of a book.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Returns
| Type | Description |
|---|---|
| CatalogItem[] | Catalog item list. |
Error codes
| ID | Error Message |
|---|---|
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010002 | Invalid request. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getCatalogList();
}
private async getCatalogList(){
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
let catalogList: bookParser.CatalogItem[] = bookParserHandler.getCatalogList();
hilog.info(0x0000, 'testTag', `getCatalogList succeeded, catalogList:` + JSON.stringify(catalogList));
}
build() {
// Implement the page layout based on your service needs.
}
} getSpineList(): SpineItem[]
Obtains the spine item list.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Returns
| Type | Description |
|---|---|
| SpineItem[] | Spine item list. |
Error codes
| ID | Error Message |
|---|---|
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010002 | Invalid request. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getSpineList();
}
private async getSpineList(){
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
let spineList: bookParser.SpineItem[] = bookParserHandler.getSpineList();
hilog.info(0x0000, 'testTag', `getSpineList succeeded, spineList:` + JSON.stringify(spineList));
}
build() {
// Implement the page layout based on your service needs.
}
} getSpineItemContent(spineIndex: number): Promise<string>
Obtains the resource content of a single spine item. This API is called when the typesetting engine obtains the content of a resource file. If you do not need to customize the typesetting engine, you can ignore this API. This API returns the result asynchronously through a promise.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| spineIndex | number | Yes | Content resource index (SpineItem.index). |
Returns
| Type | Description |
|---|---|
| Promise<string> | Promise used to return the content string of a spine item. |
Error codes
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types; 2. Parameter out of range. |
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010001 | Invalid spine item. |
| 1017010002 | Invalid request. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getSpineItemContent();
}
private async getSpineItemContent(){
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
let spineList: bookParser.SpineItem[] = bookParserHandler.getSpineList();
let spineItemContent: string = await bookParserHandler.getSpineItemContent(spineList[0].index);
hilog.info(0x0000, 'testTag', `getSpineItemContent succeeded, spineItemContent:` + JSON.stringify(spineItemContent));
}
build() {
// Implement the page layout based on your service needs.
}
} getResourceContent(spineIndex: number, filePath: string): ArrayBuffer
Obtains book content resources.
You can use this API to obtain book cover resources. This API is preferentially called for the typesetting engine to obtain book resources such as images. If no resource is obtained, call on('resourceRequest').
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| spineIndex | number | Yes | Content resource index (SpineItem.index). If a negative number, for example, -1, is passed, the book cover is obtained. |
| filePath | string | Yes | Relative path of a resource file in a book. |
Returns
| Type | Description |
|---|---|
| ArrayBuffer | Binary data of a file. |
Error codes
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types; 2. Parameter out of range. |
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010001 | Invalid spine item. |
| 1017010002 | Invalid request. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getResourceContent();
}
private async getResourceContent() {
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
// Replace the value with an actual image name in the book file.
let imagePath = './2188093923226426261_image001.jpg'
let spineList: bookParser.SpineItem[] = bookParserHandler.getSpineList();
let resourceContent: ArrayBuffer = bookParserHandler.getResourceContent(spineList[0].index, imagePath);
hilog.info(0x0000, 'testTag', `getResourceContent succeeded, resourceContentByteLength:` + resourceContent.byteLength);
}
build() {
// Implement the page layout based on your service needs.
}
} getDomPosByCatalogHref(href: string): string
Obtains the reading start position domPos, which can be used to identify the reading progress, facilitating navigation to a specified reading position.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| href | string | Yes | Content resource path of a catalog item with an anchor (CatalogItem.href). |
Returns
| Type | Description |
|---|---|
| string | domPos information of a chapter. |
Error codes
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types; 2. Parameter out of range. |
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010002 | Invalid request. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getDomPosByCatalogHref();
}
private async getDomPosByCatalogHref(){
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
let catalogList: bookParser.CatalogItem[] = bookParserHandler.getCatalogList();
let href = catalogList[1]?.href || '';
let domPos: string = bookParserHandler.getDomPosByCatalogHref(href);
hilog.info(0x0000, 'testTag', `getDomPosByCatalogHref succeeded, domPos:` + domPos);
}
build() {
// Implement the page layout based on your service needs.
}
} getAbsoluteResourcePath(spineIndex: number): string
Obtains the complete file path of a resource.
This API is typically called when the typesetting engine renders a resource. If typesetting engine customization is not required, you can ignore this API.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 5.0.4(16).
System capability: SystemCapability.Reader.ReaderService.BookParser
Since: 5.0.4(16)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| spineIndex | number | Yes | Content resource index (SpineItem.index). |
Returns
| Type | Description |
|---|---|
| string | Complete path of a resource. |
Error codes
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types; 2. Parameter out of range. |
| 1017000001 | Book parser is not initialized. |
| 1017000999 | Other error. |
| 1017010002 | Invalid request. |
| 1017010004 | File is not exist. |
Example:
import { bookParser } from '@kit.ReaderKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Reader {
aboutToAppear(): void {
this.getAbsoluteResourcePath();
}
private async getAbsoluteResourcePath(){
// Initialize the book parser for the book file that has been imported to the app sandbox directory.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let filePath: string = `${context.filesDir}/abc.epub`;
let bookParserHandler: bookParser.BookParserHandler = await bookParser.getDefaultHandler(filePath);
let spineList: bookParser.SpineItem[] = bookParserHandler.getSpineList();
let resourcePath: string = bookParserHandler.getAbsoluteResourcePath(spineList[0].index);
hilog.info(0x0000, 'testTag', `getAbsoluteResourcePath succeeded, resourcePath:` + resourcePath);
}
build() {
// Implement the page layout based on your service needs.
}
}