### Install LiteOfd with npm
Source: https://github.com/signitdoc/liteofd/blob/master/docs/index.html
Install the LiteOfd library using npm. Note that there might be issues with font loading in npm packages, so consider using source imports.
```bash
npm install liteofd
```
--------------------------------
### LiteOfd Initialization and Basic Usage
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
Demonstrates how to install LiteOfd and perform basic file parsing and rendering.
```APIDOC
## Installation
Use npm to install LiteOfd:
```bash
npm install liteofd
```
**Note:** There are current issues with the npm package regarding font file loading. It is recommended to import from source or contribute to fixing the packaging script. Contact QQ: 897761547 for assistance.
## Basic Usage Example
Parse an OFD file and render it to a display component.
```typescript
import { LiteOfd } from 'liteofd'
function parseOfdFile(file: File) {
const liteOfd = new LiteOfd()
let appContent = document.getElementById("ofd-content")
appContent.innerHTML = ''
liteOfd.parse(file).then((data: OfdDocument) => {
console.log('Parsed OFD file successfully:', data);
let ofdDiv = liteOfd.render(undefined, 'background-color: white; margin-top: 12px;')
appContent.appendChild(ofdDiv) //
}).catch((error) => {
console.error('Failed to parse OFD file:', error);
});
}
```
```
--------------------------------
### Execute Action in OFD
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This example shows how to execute a specific action within the OFD document, such as navigating to a page, using provided action data.
```typescript
// 假设 action 是从大纲数据中获取的
liteOfd.executeAction(action);
```
--------------------------------
### Listen for Signature Element Click Event
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This example demonstrates how to listen for the `signature-element-click` event. When a signature element is clicked, it logs the `nodeData` and `sealObject` from the event details and calls `displaySignatureDetails`.
```typescript
appContent.addEventListener('signature-element-click', (event: CustomEvent) => {
const { nodeData, sealObject } = event.detail;
console.log('Clicked Signature Element:', nodeData);
console.log('Seal Object:', sealObject);
// 显示签名详情
displaySignatureDetails(nodeData, sealObject);
});
```
--------------------------------
### Render OFD Document
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This example demonstrates how to render an OFD document into a specified HTML element with custom styling for the page wrapper.
```typescript
let renderDiv = liteOfd.render(undefined, 'background-color: white; margin-top: 12px;')
document.getElementById('content').appendChild(renderDiv);
```
--------------------------------
### Parse OFD File with LiteOfd
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This TypeScript example shows how to parse an OFD file using the `parseFile` method. It logs the parsed document data or any errors encountered.
```typescript
const fileInput = document.getElementById('fileInput') as HTMLInputElement;
const file = fileInput.files?.[0];
if (file) {
liteOfd.parseFile(file).then((data: OfdDocument) => {
console.log('解析OFD文件成功:', data);
}).catch((error) => {
console.error('解析OFD文件失败:', error);
});
}
```
--------------------------------
### Parse and Render OFD File
Source: https://github.com/signitdoc/liteofd/blob/master/docs/index.html
Example of parsing an OFD file using LiteOfd and rendering its content. Ensure the target element for rendering is available in the DOM.
```typescript
import { LiteOfd } from 'liteofd'
function parseOfdFile(file: File) {
const liteOfd = new LiteOfd()
let appContent = getElementById("ofd-content")
appContent.innerHTML = ''
liteOfd.parse(file).then((data: OfdDocument) => {
console.log('解析OFD文件成功:', data);
let ofdDiv = liteOfd.render(undefined, 'background-color: white; margin-top: 12px;')
appContent.appendChild(ofdDiv)
}).catch((error) => {
console.error('解析OFD文件失败:', error);
});
}
```
--------------------------------
### Get Total Pages
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet retrieves and logs the total number of pages in the OFD document.
```typescript
const totalPages = liteOfd.getTotalPages();
console.log(`总页数:${totalPages}`);
```
--------------------------------
### Get Current Page Index
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet retrieves and logs the index of the currently displayed page in the OFD document.
```typescript
const currentPage = liteOfd.getCurrentPageIndex();
console.log(`当前页面:${currentPage}`);
```
--------------------------------
### Get Document Content
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet retrieves and logs the text content of a specific page or the entire OFD document.
```typescript
const content = liteOfd.getContentText(null);
console.log("文档内容:", content);
```
--------------------------------
### Get Document Text Content with LiteOfd
Source: https://context7.com/signitdoc/liteofd/llms.txt
The getContent() method extracts text from the entire document or specific pages. This is useful for text searching and content indexing. Page numbers are 1-based.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
liteOfd.parse(file).then(() => {
// 获取整个文档的全部文本
const allContent = liteOfd.getContent()
console.log('文档全部内容:', allContent)
// 获取指定页面的文本(页码从1开始)
const page1Content = liteOfd.getContent(1)
console.log('第1页内容:', page1Content)
const page2Content = liteOfd.getContent(2)
console.log('第2页内容:', page2Content)
// 实现简单的关键词搜索
const keyword = '发票'
if (allContent.includes(keyword)) {
console.log(`文档中包含关键词: ${keyword}`)
}
// 遍历所有页面提取文本
for (let i = 1; i <= liteOfd.totalPages; i++) {
const pageText = liteOfd.getContent(i)
console.log(`第${i}页文本长度: ${pageText.length}`)
}
})
```
--------------------------------
### LiteOfd Initialization
Source: https://context7.com/signitdoc/liteofd/llms.txt
Initializes the LiteOfd instance which serves as the primary entry point for document processing.
```APIDOC
## LiteOfd Initialization
### Description
Creates a new instance of the LiteOfd class to manage OFD document operations.
### Properties
- **currentPage** (number) - The current page index of the document.
- **totalPages** (number) - The total number of pages in the document.
```
--------------------------------
### Action Execution and Event Handling
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
Methods for executing actions and listening to document events.
```APIDOC
## `executeAction(action: XmlData)`
### Description
Executes a specified action, such as navigating to a specific page.
### Method
`executeAction`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **action** (XmlData) - Required - The action data to execute.
### Example
```typescript
// Assume action is obtained from outline data
liteOfd.executeAction(action);
```
## Event: `ofdPageChange`
### Description
Fired when the OFD document page changes.
### Example
```typescript
window.addEventListener('ofdPageChange', (event: CustomEvent) => {
// Update page information display
updatePageInfo();
});
```
## Event: `signature-element-click`
### Description
Fired when a signature element is clicked.
### Example
```typescript
appContent.addEventListener('signature-element-click', (event: CustomEvent) => {
const { nodeData, sealObject } = event.detail;
console.log('Clicked Signature Element:', nodeData);
console.log('Seal Object:', sealObject);
// Display signature details
displaySignatureDetails(nodeData, sealObject);
});
```
```
--------------------------------
### Initialize LiteOfd Instance
Source: https://context7.com/signitdoc/liteofd/llms.txt
Create a new LiteOfd instance to access core document processing features and properties.
```typescript
import { LiteOfd } from 'liteofd'
// 创建 LiteOfd 实例
const liteOfd = new LiteOfd()
// 实例属性
console.log(liteOfd.currentPage) // 当前页码 (number)
console.log(liteOfd.totalPages) // 总页数 (number)
```
--------------------------------
### Page Navigation Methods
Source: https://context7.com/signitdoc/liteofd/llms.txt
Methods for navigating through the pages of the rendered OFD document.
```APIDOC
## Navigation Methods
### Methods
- **goToPage(pageNumber)** - Navigates to the specified page number.
- **nextPage()** - Navigates to the next page.
- **prevPage()** - Navigates to the previous page.
```
--------------------------------
### Page Navigation and Zoom Controls
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
Methods for navigating between pages and controlling zoom levels.
```APIDOC
## `getCurrentPageIndex(): number`
### Description
Gets the current page index.
### Method
`getCurrentPageIndex`
### Response
#### Success Response (200)
- **number** - The index of the current page.
### Example
```typescript
const currentPage = liteOfd.getCurrentPageIndex();
console.log(`Current page: ${currentPage}`);
```
## `getTotalPages(): number`
### Description
Gets the total number of pages in the document.
### Method
`getTotalPages`
### Response
#### Success Response (200)
- **number** - The total number of pages.
### Example
```typescript
const totalPages = liteOfd.getTotalPages();
console.log(`Total pages: ${totalPages}`);
```
## `nextPage()`
### Description
Navigates to the next page.
### Method
`nextPage`
### Example
```typescript
liteOfd.nextPage();
```
## `prevPage()`
### Description
Navigates to the previous page.
### Method
`prevPage`
### Example
```typescript
liteOfd.prevPage();
```
## `scrollToPage(pageIndex: number)`
### Description
Scrolls to a specified page.
### Method
`scrollToPage`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **pageIndex** (number) - Required - The index of the target page.
### Example
```typescript
liteOfd.scrollToPage(1); // Scrolls to the first page
```
## `zoomIn()`
### Description
Zooms in on the document.
### Method
`zoomIn`
### Example
```typescript
liteOfd.zoomIn();
```
## `zoomOut()`
### Description
Zooms out on the document.
### Method
`zoomOut`
### Example
```typescript
liteOfd.zoomOut();
```
## `resetZoom()`
### Description
Resets the document zoom level.
### Method
`resetZoom`
### Example
```typescript
liteOfd.resetZoom();
```
```
--------------------------------
### Implement signature-element-click event listener
Source: https://context7.com/signitdoc/liteofd/llms.txt
Use this event to capture user interactions with electronic signatures. Ensure the event is stopped from propagating to prevent unintended side effects.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
const appContent = document.getElementById('content') as HTMLDivElement
liteOfd.parse(file).then((data) => {
appContent.innerHTML = ''
appContent.appendChild(liteOfd.render())
// 监听签章点击事件
appContent.addEventListener('signature-element-click', (event: Event) => {
event.stopPropagation()
const customEvent = event as CustomEvent
const { nodeData, sealObject } = customEvent.detail
console.log('点击的签章节点:', nodeData)
console.log('印章对象:', sealObject)
// 显示签章详情弹窗
const detailsContainer = document.getElementById('signature-details')
if (detailsContainer) {
detailsContainer.innerHTML = `
电子签章详情
签章类型: ${sealObject?.type || '未知'}
节点数据: ${JSON.stringify(nodeData, null, 2)}
印章数据: ${JSON.stringify(sealObject, null, 2)}
`
detailsContainer.style.display = 'block'
}
})
// 点击其他地方关闭弹窗
document.addEventListener('click', (event) => {
const detailsContainer = document.getElementById('signature-details')
if (detailsContainer && !detailsContainer.contains(event.target as Node)) {
detailsContainer.style.display = 'none'
}
})
})
```
--------------------------------
### Render Individual Pages
Source: https://context7.com/signitdoc/liteofd/llms.txt
Render specific pages by index, useful for previews or thumbnail generation.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
liteOfd.parse(file).then(() => {
// 渲染第一页(索引从0开始)
const page1 = liteOfd.renderPage(0, 'background-color: #fff;')
document.getElementById('page-preview-1')?.appendChild(page1)
// 渲染第二页
const page2 = liteOfd.renderPage(1, 'background-color: #fff;')
document.getElementById('page-preview-2')?.appendChild(page2)
// 创建缩略图预览
for (let i = 0; i < liteOfd.totalPages; i++) {
const thumbnail = liteOfd.renderPage(i, 'transform: scale(0.2); transform-origin: top left;')
document.getElementById('thumbnails')?.appendChild(thumbnail)
}
})
```
--------------------------------
### Navigate OFD Pages
Source: https://context7.com/signitdoc/liteofd/llms.txt
Control document navigation using methods like goToPage, nextPage, and prevPage.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
// 解析和渲染后进行页面导航
liteOfd.parse(file).then(() => {
liteOfd.render()
// 跳转到第一页
liteOfd.goToPage(1)
// 跳转到最后一页
liteOfd.goToPage(liteOfd.totalPages)
// 跳转到指定页面
liteOfd.goToPage(5)
// 下一页
liteOfd.nextPage()
// 上一页
liteOfd.prevPage()
// 获取当前页码
console.log('当前页:', liteOfd.currentPage)
})
// 绑定导航按钮
document.getElementById('btn-first')?.addEventListener('click', () => liteOfd.goToPage(1))
document.getElementById('btn-prev')?.addEventListener('click', () => liteOfd.prevPage())
document.getElementById('btn-next')?.addEventListener('click', () => liteOfd.nextPage())
document.getElementById('btn-last')?.addEventListener('click', () => liteOfd.goToPage(liteOfd.totalPages))
```
--------------------------------
### 构建完整的 OFD 文档查看器
Source: https://context7.com/signitdoc/liteofd/llms.txt
展示了从文件上传、文档解析到页面导航和签章点击事件处理的完整集成流程。
```typescript
import { LiteOfd } from 'liteofd'
import { OfdDocument } from 'liteofd'
// 初始化
const liteOfd = new LiteOfd()
const appContent = document.getElementById('content') as HTMLDivElement
// 文件上传处理
function handleFileUpload(event: Event) {
const fileInput = event.target as HTMLInputElement
const file = fileInput.files?.[0]
if (!file || !file.name.toLowerCase().endsWith('.ofd')) {
alert('请选择 .ofd 文件')
return
}
// 显示加载状态
appContent.innerHTML = '正在解析文档...
'
// 解析并渲染
liteOfd.parse(file)
.then((data: OfdDocument) => {
console.log('解析成功:', data)
// 清空并渲染
appContent.innerHTML = ''
const renderedDiv = liteOfd.render(undefined, 'background-color: white; margin-top: 12px;')
appContent.appendChild(renderedDiv)
// 更新页面信息
updatePageInfo()
// 渲染大纲(如果有)
if (data.outlines?.children?.length > 0) {
renderOutlines(data.outlines)
}
})
.catch((error) => {
console.error('解析失败:', error)
appContent.innerHTML = '解析文件失败,请检查文件格式
'
})
}
// 更新页面信息
function updatePageInfo() {
const pageInfo = document.querySelector('.page-info')
if (pageInfo) {
pageInfo.textContent = `${liteOfd.currentPage} / ${liteOfd.totalPages}`
}
}
// 监听页面变化
window.addEventListener('ofdPageChange', updatePageInfo)
// 监听签章点击
appContent.addEventListener('signature-element-click', (event: Event) => {
const { nodeData, sealObject } = (event as CustomEvent).detail
showSignatureModal(nodeData, sealObject)
})
// 导航控制
document.getElementById('btn-first')?.addEventListener('click', () => liteOfd.goToPage(1))
document.getElementById('btn-prev')?.addEventListener('click', () => liteOfd.prevPage())
document.getElementById('btn-next')?.addEventListener('click', () => liteOfd.nextPage())
document.getElementById('btn-last')?.addEventListener('click', () => liteOfd.goToPage(liteOfd.totalPages))
// 缩放控制
document.getElementById('btn-zoom-in')?.addEventListener('click', () => liteOfd.zoomIn())
document.getElementById('btn-zoom-out')?.addEventListener('click', () => liteOfd.zoomOut())
document.getElementById('btn-zoom-reset')?.addEventListener('click', () => liteOfd.resetZoom())
// 文件输入绑定
document.getElementById('fileInput')?.addEventListener('change', handleFileUpload)
```
--------------------------------
### renderPage() - Render Single Page
Source: https://context7.com/signitdoc/liteofd/llms.txt
Renders a specific page of the OFD document as an HTML element.
```APIDOC
## renderPage(pageIndex, style)
### Description
Returns an HTMLDivElement representing a specific page of the document.
### Parameters
- **pageIndex** (number) - Required - The zero-based index of the page to render.
- **style** (string) - Optional - CSS styles to apply to the page element.
```
--------------------------------
### Navigate to Previous Page
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet calls the `prevPage` method to go back to the previous page of the OFD document.
```typescript
liteOfd.prevPage();
```
--------------------------------
### Parse and Render OFD File
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This TypeScript code demonstrates how to parse an OFD file and render its content into a specified HTML element. It handles file input and appends the rendered OFD to a div.
```typescript
import { LiteOfd } from 'liteofd'
function parseOfdFile(file: File) {
const liteOfd = new LiteOfd()
let appContent = getElementById("ofd-content")
appContent.innerHTML = ''
liteOfd.parse(file).then((data: OfdDocument) => {
console.log('解析OFD文件成功:', data);
let ofdDiv = liteOfd.render(undefined, 'background-color: white; margin-top: 12px;')
appContent.appendChild(ofdDiv) //
}).catch((error) => {
console.error('解析OFD文件失败:', error);
});
}
```
--------------------------------
### render() - Render OFD Document
Source: https://context7.com/signitdoc/liteofd/llms.txt
Renders the entire parsed OFD document into an HTML element.
```APIDOC
## render(container, style)
### Description
Converts the parsed OFD document into a scrollable HTML element.
### Parameters
- **container** (HTMLElement) - Optional - The target container for rendering.
- **style** (string) - Optional - CSS styles to apply to the rendered output.
```
--------------------------------
### Render OFD Documents
Source: https://context7.com/signitdoc/liteofd/llms.txt
Render the entire document into an HTML element. Supports custom containers and CSS styling for pages.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
const appContent = document.getElementById('content') as HTMLDivElement
// 解析并渲染文档
liteOfd.parse(file).then((data) => {
// 清空容器
appContent.innerHTML = ''
// 渲染文档,设置页面背景和间距样式
const renderedDiv = liteOfd.render(
undefined, // 不传入自定义容器,由库创建
'background-color: white; margin-top: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);'
)
// 将渲染结果添加到页面
appContent.appendChild(renderedDiv)
console.log('渲染完成,当前页:', liteOfd.currentPage, '总页数:', liteOfd.totalPages)
})
// 使用自定义容器渲染
const customContainer = document.createElement('div')
customContainer.style.cssText = 'width: 800px; height: 600px; overflow: auto;'
const rendered = liteOfd.render(customContainer, 'margin: 10px;')
document.body.appendChild(rendered)
```
--------------------------------
### executeAction()
Source: https://context7.com/signitdoc/liteofd/llms.txt
Executes actions defined within the OFD document, such as navigation.
```APIDOC
## executeAction()
### Description
Executes an action defined in the OFD document, commonly used for navigation like jumping to a specific page via an outline item.
### Parameters
#### Request Body
- **action** (object) - Required - The action object extracted from the document structure.
```
--------------------------------
### getContent()
Source: https://context7.com/signitdoc/liteofd/llms.txt
Extracts text content from the document, either for the entire document or a specific page.
```APIDOC
## getContent()
### Description
Extracts the text content of the document. Can retrieve the full text or text from a specific page index.
### Parameters
#### Query Parameters
- **pageIndex** (number) - Optional - The page number to extract text from (1-based index). If omitted, returns full document text.
```
--------------------------------
### Execute Document Actions with LiteOfd
Source: https://context7.com/signitdoc/liteofd/llms.txt
The executeAction() method allows for performing actions defined within the OFD document, such as navigating to specific pages from outlines. This is typically used for implementing directory navigation.
```typescript
import { LiteOfd } from 'liteofd'
import * as parser from 'liteofd'
import { AttributeKey, OFD_KEY } from 'liteofd'
const liteOfd = new LiteOfd()
liteOfd.parse(file).then((data) => {
liteOfd.render()
// 获取大纲数据
const outlines = data.outlines
// 渲染大纲目录
if (outlines && outlines.children && outlines.children.length > 0) {
outlines.children.forEach((outline) => {
// 获取大纲标题
const title = parser.findAttributeValueByKey(outline, AttributeKey.Title) || '无标题'
// 创建大纲项元素
const outlineItem = document.createElement('div')
outlineItem.className = 'outline-item'
outlineItem.textContent = title
// 查找关联的动作
const actions = parser.findValueByTagName(outline, OFD_KEY.Actions)
if (actions) {
const actionList = actions.children[0]
actionList?.children.forEach((action) => {
// 点击大纲项时执行动作(跳转到对应页面)
outlineItem.addEventListener('click', () => {
liteOfd.executeAction(action)
})
})
}
document.getElementById('outlines-container')?.appendChild(outlineItem)
})
}
})
```
--------------------------------
### Search Text in Document
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet demonstrates how to search for a specific keyword within the OFD document.
```typescript
liteOfd.searchText("示例关键词");
```
--------------------------------
### Navigate to Next Page
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet calls the `nextPage` method to advance to the next page of the OFD document.
```typescript
liteOfd.nextPage();
```
--------------------------------
### parse() - Parse OFD File
Source: https://context7.com/signitdoc/liteofd/llms.txt
Parses an OFD file from various input sources and returns an OfdDocument object.
```APIDOC
## parse(input)
### Description
Parses an OFD file. Supports File objects, ArrayBuffer, or URL strings.
### Parameters
#### Input
- **input** (File | ArrayBuffer | string) - Required - The OFD file source.
### Response
- **OfdDocument** (Object) - Returns a promise that resolves to an object containing pages, data, signatureList, and outlines.
```
--------------------------------
### Control Document Zoom with LiteOfd
Source: https://context7.com/signitdoc/liteofd/llms.txt
Use zoom(), zoomIn(), zoomOut(), and resetZoom() to adjust the document's scale. The zoom range is from 0.1 to 5. Event listeners can be attached to UI elements to trigger these methods.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
liteOfd.parse(file).then(() => {
liteOfd.render()
// 设置指定缩放比例 (0.1 - 5)
liteOfd.zoom(1.5) // 放大到 150%
liteOfd.zoom(0.5) // 缩小到 50%
// 放大 (默认步长 0.1)
liteOfd.zoomIn() // 放大 10%
liteOfd.zoomIn(0.2) // 放大 20%
// 缩小 (默认步长 0.1)
liteOfd.zoomOut() // 缩小 10%
liteOfd.zoomOut(0.2) // 缩小 20%
// 重置缩放到 100%
liteOfd.resetZoom()
})
// 绑定缩放按钮
document.getElementById('btn-zoom-in')?.addEventListener('click', () => liteOfd.zoomIn())
document.getElementById('btn-zoom-out')?.addEventListener('click', () => liteOfd.zoomOut())
document.getElementById('btn-zoom-reset')?.addEventListener('click', () => liteOfd.resetZoom())
// 缩放滑块控制
const zoomSlider = document.getElementById('zoom-slider') as HTMLInputElement
zoomSlider?.addEventListener('input', (e) => {
const scale = parseFloat((e.target as HTMLInputElement).value)
liteOfd.zoom(scale)
})
```
--------------------------------
### Zoom Control Methods
Source: https://context7.com/signitdoc/liteofd/llms.txt
Methods to control the zoom level of the rendered OFD document, supporting specific ratios, incremental zoom, and reset functionality.
```APIDOC
## Zoom Control Methods
### Description
Provides document zoom functionality including setting a specific ratio, zooming in, zooming out, and resetting the zoom level. The supported zoom range is 0.1 to 5.
### Methods
- **zoom(ratio: number)**: Sets the zoom ratio (0.1 - 5).
- **zoomIn(step?: number)**: Increases zoom level (default step 0.1).
- **zoomOut(step?: number)**: Decreases zoom level (default step 0.1).
- **resetZoom()**: Resets zoom to 100%.
```
--------------------------------
### OFD Document Rendering
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
API method for rendering OFD documents.
```APIDOC
## `render(container?: HTMLDivElement, pageWrapStyle?: string): HTMLDivElement`
### Description
Renders the OFD document.
### Method
`render`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **container** (HTMLDivElement) - Optional - The container element to render the OFD document into.
- **pageWrapStyle** (string) - Optional - CSS styles to apply to the page wrapper.
### Request Example
```typescript
let renderDiv = liteOfd.render(undefined, 'background-color: white; margin-top: 12px;')
document.getElementById('content').appendChild(renderDiv);
```
### Response
#### Success Response (200)
- **HTMLDivElement** - The rendered div element of the OFD document.
#### Response Example
```html
...
```
```
--------------------------------
### OfdDocument Field Descriptions
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
Detailed descriptions of the fields within the OfdDocument object.
```APIDOC
## OfdDocument Fields
### `files`
- **Type**: `any`
- **Description**: All files parsed from the OFD, i.e., original files after ZIP decompression, including file paths.
### `data`
- **Type**: `any`
- **Description**: Parsed OFD data, of type `XmlData`.
### `pages`
- **Type**: `XmlData[]`
- **Description**: Array of OFD page data.
### `ofdXml`
- **Type**: `XmlData`
- **Description**: Data from the `OFD.xml` file.
### `documentData`
- **Type**: `XmlData`
- **Description**: Data from the `document.xml` file.
### `publicRes`
- **Type**: `XmlData`
- **Description**: Data from the `publicres.xml` file.
### `documentRes`
- **Type**: `XmlData`
- **Description**: Data from the `documentRes.xml` file.
### `rootContainer`
- **Type**: `Element`
- **Description**: The root container, of type `HTMLDivElement`.
### `loadedMediaFile`
- **Type**: `Map`
- **Description**: Loaded resource images, including images, etc.
### `mediaFileList`
- **Type**: `any`
- **Description**: Multimedia file list.
### `signatures`
- **Type**: `XmlData`
- **Description**: Signature data, from the `signatures.xml` file.
### `signatureList`
- **Type**: `XmlData[]`
- **Description**: List of signature data, containing an array of `XmlData` for all signatures in `signatures.xml`.
### `outlines`
- **Type**: `XmlData`
- **Description**: Outline data list, containing data for all outlines in `ofd:Outlines`.
### `annots`
- **Type**: `XmlData`
- **Description**: Annotation data list, containing data from `ofd:Annotations`.
```
--------------------------------
### getOfdDocument()
Source: https://context7.com/signitdoc/liteofd/llms.txt
Retrieves the underlying OfdDocument object for accessing raw XML data structures.
```APIDOC
## getOfdDocument()
### Description
Returns the underlying OfdDocument object, allowing access to detailed data structures including page data, signatures, outlines, annotations, and raw XML data.
```
--------------------------------
### Define OfdDocument and XmlData interfaces
Source: https://context7.com/signitdoc/liteofd/llms.txt
Reference these interfaces to understand the structure of parsed OFD documents and XML nodes. These types are useful for extending functionality or deep inspection of document data.
```typescript
import { OfdDocument } from 'liteofd'
// OfdDocument 主要字段说明
interface OfdDocumentFields {
files: any // OFD 解压后的所有原始文件
data: any // 解析后的 OFD 数据 (XmlData)
pages: XmlData[] // 页面数据数组
ofdXml: XmlData // OFD.xml 文件数据
documentData: XmlData // document.xml 文件数据
publicRes: XmlData // publicres.xml 公共资源文件
documentRes: XmlData // documentRes.xml 文档资源文件
rootContainer: Element // 渲染的根容器元素
loadedMediaFile: Map // 已加载的媒体资源映射
mediaFileList: any // 多媒体文件列表
signatures: XmlData // signatures.xml 签名文件数据
signatureList: XmlData[] // 签名数据数组
outlines: XmlData // ofd:Outlines 大纲数据
annots: XmlData // ofd:Annotations 注释数据
}
// XmlData 节点结构
interface XmlDataFields {
attrsMap: Map // 节点属性映射
children: XmlData[] // 子节点数组
value: string // 节点文本值
tagName: string // 标签名称
fileName: string // 来源 XML 文件路径
id: string // 节点 ID 属性
signList: XmlData[] // 页面关联的签章列表
sealObject: any // 签章印章数据
sealData: OfdDocument | string | null // OFD 签章数据或图片 base64
annots: XmlData | null // 关联的注释数据
}
```
--------------------------------
### Listen for OFD Page Change Event
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet shows how to add an event listener to the `ofdPageChange` event, which is triggered whenever the OFD document's page changes. It calls `updatePageInfo` when the event occurs.
```typescript
window.addEventListener('ofdPageChange', (event: CustomEvent) => {
// 更新页面信息显示
updatePageInfo();
});
```
--------------------------------
### Render SVG Formatted XML
Source: https://github.com/signitdoc/liteofd/blob/master/test/svg.html
This section is intended for rendering SVG formatted XML. The specific code for rendering is not provided in the input.
```html
渲染 SVG 格式化 XML
```
--------------------------------
### Scroll to Specific Page
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet demonstrates how to scroll to a specific page in the OFD document by providing its index.
```typescript
liteOfd.scrollToPage(1); // 跳转到第一页
```
--------------------------------
### Access OFD Document Object with LiteOfd
Source: https://context7.com/signitdoc/liteofd/llms.txt
Use getOfdDocument() to retrieve the underlying OfdDocument object. This provides access to raw XML data, including page details, signature information, outlines, and annotations.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
liteOfd.parse(file).then(() => {
const ofdDoc = liteOfd.getOfdDocument()
// 访问文档属性
console.log('所有文件:', ofdDoc.files) // 解压后的原始文件
console.log('页面数据:', ofdDoc.pages) // XmlData[] 页面数组
console.log('OFD.xml:', ofdDoc.ofdXml) // OFD.xml 文件数据
console.log('Document:', ofdDoc.documentData) // document.xml 文件数据
console.log('公共资源:', ofdDoc.publicRes) // publicres.xml 文件数据
console.log('文档资源:', ofdDoc.documentRes) // documentRes.xml 文件数据
// 访问签名数据
console.log('签名数据:', ofdDoc.signatures) // signatures.xml 数据
console.log('签名列表:', ofdDoc.signatureList) // 签名 XmlData 数组
// 访问大纲和注释
console.log('大纲数据:', ofdDoc.outlines) // 文档大纲
console.log('注释数据:', ofdDoc.annots) // 文档注释
// 访问已加载的媒体资源
console.log('媒体文件:', ofdDoc.loadedMediaFile) // Map
})
```
--------------------------------
### Zoom In Document
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet calls the `zoomIn` method to increase the zoom level of the OFD document.
```typescript
liteOfd.zoomIn();
```
--------------------------------
### OFD Document Parsing
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
API method for parsing OFD files.
```APIDOC
## `parse(file: string | File | ArrayBuffer): Promise`
### Description
Parses an uploaded OFD file.
### Method
`parse`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **file** (File) - Required - The OFD file object uploaded by the user.
### Request Example
```typescript
const fileInput = document.getElementById('fileInput') as HTMLInputElement;
const file = fileInput.files?.[0];
if (file) {
liteOfd.parseFile(file).then((data: OfdDocument) => {
console.log('Parsed OFD file successfully:', data);
}).catch((error) => {
console.error('Failed to parse OFD file:', error);
});
}
```
### Response
#### Success Response (200)
- **OfdDocument** - An OfdDocument object upon successful parsing.
#### Response Example
```json
{
"example": "OfdDocument object"
}
```
```
--------------------------------
### ofdPageChange Event
Source: https://context7.com/signitdoc/liteofd/llms.txt
Custom event triggered when the document page changes.
```APIDOC
## ofdPageChange Event
### Description
Custom event triggered when the document page changes due to scrolling or navigation. Useful for UI synchronization.
### Event Detail
- **pageIndex** (number) - The current page index.
- **pageId** (string) - The unique identifier of the current page.
```
--------------------------------
### Listen for OFD Page Change Events
Source: https://context7.com/signitdoc/liteofd/llms.txt
The 'ofdPageChange' custom event fires when the document's page changes due to scrolling or navigation. Use this to update page information displays or synchronize thumbnail selections.
```typescript
import { LiteOfd } from 'liteofd'
const liteOfd = new LiteOfd()
// 监听页面变化事件
window.addEventListener('ofdPageChange', (event: Event) => {
const customEvent = event as CustomEvent
const { pageIndex, pageId } = customEvent.detail
console.log('页面变化:', pageIndex, pageId)
// 更新页面信息显示
const pageInfoElement = document.querySelector('.page-info')
if (pageInfoElement) {
pageInfoElement.textContent = `${pageIndex} / ${liteOfd.totalPages}`
}
// 高亮当前页面的缩略图
document.querySelectorAll('.thumbnail').forEach((thumb, index) => {
thumb.classList.toggle('active', index + 1 === pageIndex)
})
})
// 解析并渲染
liteOfd.parse(file).then(() => {
const container = document.getElementById('content') as HTMLDivElement
container.appendChild(liteOfd.render())
})
```
--------------------------------
### Text Search and Content Retrieval
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
Methods for searching text within the document and retrieving its content.
```APIDOC
## `searchText(keyword: string)`
### Description
Searches for a keyword within the document.
### Method
`searchText`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **keyword** (string) - Required - The keyword to search for.
### Example
```typescript
liteOfd.searchText("Sample Keyword");
```
## `getContent(page?: number): string`
### Description
Retrieves the text content of a specific page or the entire document.
### Method
`getContent`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **page** (number | null) - Optional - The page index. If null, retrieves the entire document content.
### Response
#### Success Response (200)
- **string** - The text content of the specified page or the entire document.
### Example
```typescript
const content = liteOfd.getContentText(null);
console.log("Document content:", content);
```
```
--------------------------------
### Parse OFD Files
Source: https://context7.com/signitdoc/liteofd/llms.txt
Parse OFD documents from File objects, URLs, or ArrayBuffers. Returns an OfdDocument object containing metadata and content.
```typescript
import { LiteOfd } from 'liteofd'
import { OfdDocument } from 'liteofd'
const liteOfd = new LiteOfd()
// 方式1: 从文件输入框获取 File 对象
const fileInput = document.getElementById('fileInput') as HTMLInputElement
const file = fileInput.files?.[0]
if (file && file.name.toLowerCase().endsWith('.ofd')) {
liteOfd.parse(file)
.then((ofdDocument: OfdDocument) => {
console.log('解析成功,总页数:', ofdDocument.pages.length)
console.log('文档数据:', ofdDocument.data)
console.log('签名列表:', ofdDocument.signatureList)
console.log('大纲数据:', ofdDocument.outlines)
})
.catch((error) => {
console.error('解析OFD文件失败:', error)
})
}
// 方式2: 从 URL 路径解析
liteOfd.parse('/path/to/document.ofd')
.then((doc) => console.log('远程文件解析成功'))
// 方式3: 从 ArrayBuffer 解析
fetch('/api/document.ofd')
.then(res => res.arrayBuffer())
.then(buffer => liteOfd.parse(buffer))
.then((doc) => console.log('二进制数据解析成功'))
```
--------------------------------
### SVG Container and Input Styles
Source: https://github.com/signitdoc/liteofd/blob/master/test/svg.html
Defines CSS styles for the SVG container and input area. Ensure these styles are applied to your HTML elements.
```css
#svgContainer {
border: 1px solid #ccc;
margin: 20px;
width: 500px;
height: 500px;
position: relative;
}
#svgInput {
width: 100%;
height: 200px;
margin-bottom: 10px;
}
.button-group {
margin-bottom: 10px;
}
```
--------------------------------
### Reset Document Zoom
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet calls the `resetZoom` method to revert the OFD document's zoom level to its default.
```typescript
liteOfd.resetZoom();
```
--------------------------------
### Zoom Out Document
Source: https://github.com/signitdoc/liteofd/blob/master/README.md
This code snippet calls the `zoomOut` method to decrease the zoom level of the OFD document.
```typescript
liteOfd.zoomOut();
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.