@neosjs/html-to-pdf
Version:
将html转换为pdf,支持中文,支持图片,支持表格,支持分页,支持水印,支持自定义页眉页脚,支持页码. 解决分页截断问题.
366 lines (293 loc) • 9.55 kB
Markdown
<div class="hero" align="center">
# HTML转PDF工具库
一个功能强大、易于使用的HTML转PDF工具库,支持中文、图片、表格、分页、水印、自定义页眉页脚、页码等功能。
![NPM Version][npm-version-image] ![Npm Month Downloads][npm-downloads-image-month] ![Node Version][node-current] ![License][license-image] ![html-to-pdf][html-to-pdf]
</div>
## ✨ 特性
- 🎯 **简单易用** - 简洁的API设计,几行代码即可生成PDF
- 🌏 **中文支持** - 完美支持中文字体和文本渲染
- 🖼️ **图片支持** - 支持各种格式的图片嵌入
- 📊 **表格支持** - 完整保留表格结构和样式
- 📄 **智能分页** - 自动处理分页,避免内容截断
- 🏷️ **水印功能** - 支持自定义水印内容和样式
- 📝 **页眉页脚** - 灵活的自定义页眉页脚配置
- 📈 **性能监控** - 内置性能监控,优化生成过程
- 🎨 **样式保持** - 最大程度保持原始HTML样式
- 🔧 **高度可配置** - 丰富的配置选项满足各种需求
## 📦 安装
```bash
npm install @neosjs/html-to-pdf
# 或
yarn add @neosjs/html-to-pdf
# 或
pnpm add @neosjs/html-to-pdf
```
## 🚀 快速开始
### 基础使用
```javascript
import HtmlToPdf from '@neosjs/html-to-pdf'
// 创建转换器实例
const converter = new HtmlToPdf({
elementId: 'my-content', // 目标元素ID
wholeNodeClass: 'no-break', // 不可分页元素的CSS类名
fileName: 'document', // 输出文件名
format: 'a4', // 纸张格式
orientation: 'p' // 页面方向
})
// 生成PDF
try {
const blob = await converter.generatePDF()
console.log('PDF生成成功:', blob.size, 'bytes')
} catch (error) {
console.error('PDF生成失败:', error)
}
```
### 高级配置
```javascript
const converter = new HtmlToPdf({
// 基本配置
elementId: 'my-content',
wholeNodeClass: 'no-break',
ignoreElementsClass: 'ignore-pdf',
intervalHeight: 10,
enablePerformanceMonitor: true,
fileName: 'advanced-document',
format: 'a4',
orientation: 'p',
// html2canvas配置
html2canvas: {
scale: 2.0,
quality: 0.9,
useCORS: true,
allowTaint: true,
backgroundColor: '#ffffff',
logging: false
},
// 页边距配置
pageMargin: {
top: 15,
bottom: 15,
left: 15,
right: 15
},
// 页眉配置
header: {
content: '文档标题',
align: 'center',
fontSize: 14,
color: '#333333',
border: true
},
// 页脚配置
footer: {
content: '第 {page} 页,共 {total} 页',
align: 'center',
fontSize: 10,
color: '#666666'
},
// 水印配置
watermark: {
content: '机密文档',
color: '#ff0000',
size: 20,
angle: 45,
opacity: 0.3
},
// 自动打开PDF
open: true
})
```
## 📚 API文档
### 配置选项
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `elementId` | `string \| HTMLElement` | - | 目标DOM元素ID或元素本身(必填) |
| `wholeNodeClass` | `string` | - | 不可分页元素的CSS类名(必填) |
| `ignoreElementsClass` | `string` | - | 需要忽略的元素的CSS类名 |
| `intervalHeight` | `number` | `5` | 元素间距(像素) |
| `enablePerformanceMonitor` | `boolean` | `false` | 是否启用性能监控 |
| `fileName` | `string` | `"导出"` | 输出文件名(不含扩展名) |
| `format` | `PaperFormat` | `"a4"` | 纸张格式 |
| `orientation` | `Orientation` | `"portrait"` | 页面方向 |
| `html2canvas` | `Html2CanvasOptions` | - | html2canvas配置选项 |
| `header` | `HeaderFooter` | - | 页眉配置 |
| `footer` | `HeaderFooter` | - | 页脚配置 |
| `pageMargin` | `PageMargin` | - | 页边距配置 |
| `watermark` | `Watermark` | - | 水印配置 |
| `open` | `boolean` | `false` | 是否自动打开PDF文件 |
### 纸张格式
支持以下纸张格式:
- `a0`, `a1`, `a2`, `a3`, `a4`, `a5`, `a6`, `a7`, `a8`
- `letter`, `legal`, `tabloid`, `ledger`
### 页面方向
- `p` 或 `portrait` - 纵向
- `l` 或 `landscape` - 横向
### html2canvas配置
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `scale` | `number` | `1.5` | 缩放比例 |
| `quality` | `number` | `0.75` | 图片质量(0-1) |
| `useCORS` | `boolean` | `true` | 是否使用CORS |
| `allowTaint` | `boolean` | `true` | 是否允许跨域图片 |
| `backgroundColor` | `string` | `"#ffffff"` | 背景颜色 |
| `logging` | `boolean` | `false` | 是否开启日志 |
### 页眉页脚配置
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `content` | `string \| string[]` | - | 内容文本,支持数组形式的多行文本 |
| `align` | `Alignment` | `"center"` | 对齐方式 |
| `color` | `string` | `"#333"` | 文本颜色 |
| `fontSize` | `number` | `10` | 字体大小 |
| `fontWeight` | `number` | `400` | 字体粗细 |
| `border` | `boolean` | `false` | 是否显示边框 |
### 水印配置
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `content` | `string` | - | 水印内容文本 |
| `color` | `string` | `"#ddd"` | 水印颜色 |
| `size` | `number` | `14` | 水印字体大小 |
| `angle` | `number` | `45` | 水印旋转角度 |
| `opacity` | `number` | `0.2` | 水印透明度(0-1) |
### 页边距配置
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `top` | `number` | `10` | 上边距(毫米) |
| `bottom` | `number` | `10` | 下边距(毫米) |
| `left` | `number` | `10` | 左边距(毫米) |
| `right` | `number` | `10` | 右边距(毫米) |
## 🔧 使用方法
### 1. 准备HTML结构
```html
<div id="my-content">
<div class="no-break">
<!-- 不可分页的内容 -->
<h1>标题</h1>
<p>段落内容...</p>
</div>
<div class="ignore-pdf">
<!-- 忽略的内容 -->
</div>
</div>
```
### 2. 创建转换器
```javascript
const converter = new HtmlToPdf({
elementId: 'my-content',
wholeNodeClass: 'no-break',
ignoreElementsClass: 'ignore-pdf'
})
```
### 3. 生成PDF
```javascript
try {
const blob = await converter.generatePDF()
// 下载PDF
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'document.pdf'
a.click()
URL.revokeObjectURL(url)
} catch (error) {
console.error('PDF生成失败:', error)
}
```
## 📊 性能监控
启用性能监控可以分析PDF生成过程中的各个步骤:
```javascript
const converter = new HtmlToPdf({
elementId: 'my-content',
wholeNodeClass: 'no-break',
enablePerformanceMonitor: true
})
try {
const blob = await converter.generatePDF()
// 获取性能报告
const report = converter.getReport()
console.log('性能报告:', report)
// 打印详细报告
converter.printSummary()
// 获取所有日志
const logs = converter.getLogs()
console.log('性能日志:', logs)
// 导出性能数据
const data = converter.exportData()
console.log('性能数据:', data)
} catch (error) {
console.error('PDF生成失败:', error)
}
```
## 🎯 最佳实践
### 1. 不可分页元素处理
使用 `wholeNodeClass` 标记不可分页的元素:
```html
<div class="no-break">
<h1>标题</h1>
<p>这个段落不会被分页截断</p>
</div>
```
### 2. 忽略不需要的元素
使用 `ignoreElementsClass` 忽略不需要的元素:
```html
<div class="ignore-pdf">
<button>这个按钮不会出现在PDF中</button>
</div>
```
### 3. 优化图片质量
```javascript
const converter = new HtmlToPdf({
elementId: 'my-content',
wholeNodeClass: 'no-break',
html2canvas: {
scale: 2.0, // 提高缩放比例
quality: 0.9, // 提高图片质量
useCORS: true, // 启用CORS
allowTaint: true // 允许跨域图片
}
})
```
### 4. 自定义页眉页脚
```javascript
const converter = new HtmlToPdf({
elementId: 'my-content',
wholeNodeClass: 'no-break',
header: {
content: ['公司名称', '文档标题'],
align: 'center',
fontSize: 12,
color: '#333',
border: true
},
footer: {
content: '生成时间: {date} | 第 {page} 页,共 {total} 页',
align: 'center',
fontSize: 10,
color: '#666'
}
})
```
## 🐛 错误处理
库提供了详细的错误信息和错误代码:
```javascript
try {
const blob = await converter.generatePDF()
} catch (error) {
console.error('错误类型:', error.code)
console.error('错误信息:', error.message)
console.error('错误详情:', error.details)
}
```
常见错误代码:
- `ELEMENT_NOT_FOUND` - 未找到目标DOM元素
- `EMPTY_ELEMENT` - 目标元素为空
- `CANVAS_GENERATION_FAILED` - Canvas生成失败
- `PDF_CREATION_FAILED` - PDF创建失败
- `MEMORY_ERROR` - 内存错误
- `INVALID_OPTIONS` - 配置选项无效
## License
[MIT](./LICENSE) License © 2021 - PRESENT [NeosJS](https://docs.neosjs.com/)
[npm-version-image]: https://img.shields.io/npm/v/@neosjs/html-to-pdf?style=flat&colorA=2d333b&colorB=1fa669
[npm-downloads-image-month]: https://img.shields.io/npm/dm/@neosjs/html-to-pdf?style=flat&colorA=2d333b&colorB=1fa669
[license-image]: https://img.shields.io/npm/l/@neosjs/html-to-pdf?style=flat&colorA=2d333b&colorB=1fa669
[html-to-pdf]: https://img.shields.io/badge/NeosJS-html--to--pdf-1fa669?style=flat&colorA=2d333b&colorB=1fa669
[node-current]: https://img.shields.io/node/v/@neosjs/html-to-pdf?style=flat&colorA=2d333b&colorB=1fa669