erp-print
Version:
A Vue3 + TypeScript + Element Plus based hiprint component library
426 lines (335 loc) • 11.5 kB
Markdown
[](./README.md) | [中文](./README.zh-CN.md)
---
A modern Hiprint + Vue3 + TypeScript + Element Plus based print component library.
```bash
npm install erp-print
```
- Vue 3.x
- Element Plus 2.x
- TypeScript
1. Import and use the component:
```vue
<template>
<PrintDesigner
v-model="templateData"
:config="designerConfig"
@template-init="handleInit"
@template-change="handleChange"
@print-success="handlePrintSuccess"
@business-fields-refresh="handleBusinessFieldsRefresh"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { PrintDesigner } from 'erp-print'
import type { PrintDesignerConfig, TemplateData } from 'erp-print'
const templateData = ref<TemplateData>({
baseForm: { name: 'My Template' },
templateJson: {},
})
const designerConfig = ref<PrintDesignerConfig>({
upload: {
action: '/api/upload',
allowedTypes: ['image/jpeg', 'image/png'],
maxSizeInMB: 5,
},
businessFields: {
fields: [], // Your business fields
async: true, // Enable async mode for loading state management
isLoading: false, // Loading state managed in config
loadingText: 'Loading business fields...',
},
})
const handleInit = (printInstance) => {
console.log('Designer initialized:', printInstance)
}
const handleChange = (data: TemplateData) => {
console.log('Template changed:', data)
}
const handlePrintSuccess = (result) => {
console.log('Print successful:', result)
}
const handleBusinessFieldsRefresh = () => {
console.log('Business fields refresh requested')
// Start loading
if (designerConfig.value.businessFields) {
designerConfig.value.businessFields.isLoading = true
}
// Simulate async data fetching
setTimeout(() => {
// Update your business fields here
if (designerConfig.value.businessFields) {
designerConfig.value.businessFields.fields = [
/* your new fields */
]
// End loading
designerConfig.value.businessFields.isLoading = false
}
}, 1000)
}
</script>
```
For more detailed examples, please check the ExampleDemo.vue file in the source code.
- 🎨 Modern print template designer
- 📄 Multiple paper sizes and orientations
- 🖼️ Rich element types (text, image, table, etc.)
- 🌐 Multi-language support
- 📱 Responsive design
- 🔧 TypeScript support
- ⚡ Real-time preview
- 📋 Business field integration
### API Reference
#### `PrintDesigner` Component
##### **Config Prop**
The `PrintDesigner` component is configured via the `config` prop, which accepts an object of type `PrintDesignerConfig`.
```typescript
interface PrintDesignerConfig {
// Upload configuration for images
upload?: {
action?: string
allowedTypes?: string[]
maxSizeInMB?: number
headers?: Record<string, string>
data?: Record<string, any>
}
// Business fields for drag-and-drop
businessFields?: {
fields?: BusinessFieldGroup[]
async?: boolean
isLoading?: boolean
loadingText?: string
}
// Custom control elements for the sidebar
customControlList?: ControlItem[]
}
```
| Event Name | Parameters | Description |
| ------------------------- | ----------------------- | ----------------------- |
| `template-init` | `(printInstance: any)` | Template initialized |
| `template-change` | `(data: TemplateData)` | Template data changed |
| `template-error` | `(error: any)` | Template error occurred |
| `print-success` | `(result: object)` | Print successful |
| `print-error` | `(error: object)` | Print failed |
| `export-success` | `(result: object)` | Export successful |
| `export-error` | `(error: object)` | Export failed |
| `business-fields-refresh` | `()` | Refresh business fields |
| `cancel` | `()` | Cancel operation |
| `save` | `(printInstance, data)` | Save template |
When you get a `ref` to the `PrintDesigner` component, you can call the following methods:
```vue
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { PrintDesigner } from 'erp-print'
const designerRef = ref<InstanceType<typeof PrintDesigner>>()
onMounted(() => {
// Call methods after component is mounted
designerRef.value?.init()
})
</script>
```
| Method Name | Parameters | Description |
| ------------------------- | ------------------ | -------------------------------------- |
| `init()` | `void` | Initializes the designer |
| `getPrintInstance()` | `void` | Gets the underlying hiprint instance |
| `getConfig()` | `void` | Gets the current resolved config |
| `refreshBusinessFields()` | `void` | Refreshes business fields (async mode) |
| `printAction()` | `(params: object)` | Programmatically triggers printing |
| `exportPDF()` | `(params: object)` | Programmatically triggers PDF export |
##### **Slots**
| Slot Name | Description |
| ------------------- | ---------------------- |
| `custom-header-btn` | Custom header buttons |
| `custom-form` | Custom form in sidebar |
---
#### `TemplatePreview` Component
The `TemplatePreview` component is a dialog used for previewing, printing, and exporting a hiprint template. It is controlled via a `ref` and its `show` method.
##### **Usage**
```vue
<template>
<div>
<el-button @click="showPreview">Show Preview</el-button>
<!--
The preview component can be placed anywhere in your template.
It is invisible until the `show` method is called.
-->
<TemplatePreview ref="previewRef" />
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { TemplatePreview, hiprint } from 'erp-print'
import type { TemplateData } from 'erp-print'
// 1. Get a ref to the component
const previewRef = ref<InstanceType<typeof TemplatePreview>>()
// 2. Prepare your template JSON and data
// In a real application, you would get this from the PrintDesigner or your backend
const templateJson = {
panels: [
/* ... your template json ... */
],
}
const printData: TemplateData = { baseForm: { name: 'Preview' }, templateJson: templateJson }
// Create a hiprint template instance
const hiprintTemplate = new hiprint.PrintTemplate({
template: printData.templateJson,
})
// 3. Call the `show` method to open the dialog
const showPreview = () => {
previewRef.value?.show(hiprintTemplate, printData)
}
</script>
```
| Method Name | Parameters | Description |
| ----------- | ------------------------------------------------ | ------------------------ |
| `show()` | `(hiprintTemplate, printData, options?: object)` | Shows the preview dialog |
The library is written in TypeScript and exports all necessary types for a fully typed development experience. You can import them directly from the package.
```typescript
import type {
PrintDesignerConfig,
TemplateData,
BusinessFieldGroup,
ControlItem,
// ... and other types
} from 'erp-print'
```
- Standard paper sizes (A4, A3, Letter, etc.)
- Custom paper size with width and height in mm
- Paper rotation support
#### 2. Element Types
- **Text**: Basic text elements
- **Long Text**: Multi-line text
- **Image**: Image upload and display
- **Table**: Data tables with customizable columns
- **Rectangle**: Rectangular shapes
- **Horizontal Line**: Horizontal dividers
- **Vertical Line**: Vertical dividers
- **Oval**: Oval shapes
- **HTML**: Custom HTML content
#### 3. Business Field Types
- **Configuration Fields**: Standard business data fields
- **Table Fields**: Dynamic table columns
#### 4. Operations
- **Scale adjustment**: Zoom in/out
- **Paper rotation**: Rotate template
- **Clear template**: Remove all elements
- **JSON view**: View template structure
- **Print preview**: Preview before printing
- **Export to PDF**: Multiple export formats
- **Undo/Redo**: Operation history
### Development
```bash
# Install dependencies
npm install
# Start development server
npm run dev
# Build library
npm run build
# Build demo
npm run build-demo
# Type check
npm run type-check
# Lint and format
npm run lint
npm run format
# Package and publish
npm run package # Patch version
npm run package:minor # Minor version
npm run package:major # Major version
npm run package:beta # Beta version
```
### Internationalization (i18n)
erp-print supports multi-language with automatic hiprint synchronization.
#### Supported Languages
- `cn` - 简体中文 (Simplified Chinese)
- `en` - English
- `de` - Deutsch (German)
- `es` - Español (Spanish)
- `fr` - Français (French)
- `it` - Italiano (Italian)
- `ja` - 日本語 (Japanese)
- `ru` - Русский (Russian)
- `cn_tw` - 繁體中文 (Traditional Chinese)
#### Language Features
- 🔄 **Auto-sync with hiprint**
- 💾 **Persistent storage**
- 🌐 **Browser detection**
- 🔧 **Programmatic control**
- 📦 **Built-in translations**
The language system is automatically managed by the PrintDesigner component. Users can switch languages using the built-in language dropdown in the toolbar.
### Advanced Configuration
For complex business scenarios, you can extend the component with custom configurations:
```typescript
// Advanced business fields configuration
const advancedConfig: PrintDesignerConfig = {
upload: {
action: '/api/upload',
headers: {
Authorization: 'Bearer your-token',
},
// Custom upload data transform
data: {
module: 'print-templates',
category: 'invoices',
},
},
businessFields: {
fields: [
{
id: 'invoice',
typeName: 'Invoice Fields',
variables: [
{
id: '1',
name: 'Invoice Number',
field: 'invoiceNo',
fieldType: 'normal',
defaultValue: 'INV-001',
},
// ... more fields
],
defaultExpand: true,
},
],
async: true,
loadingText: 'Loading business fields...',
},
}
```
1. **Type Safety**
```typescript
// Always use TypeScript for better development experience
import type { PrintDesignerConfig } from 'erp-print'
```
2. **Performance**
```typescript
// Use async loading for large business field datasets
const config = {
businessFields: {
async: true,
fields: [], // Load dynamically
},
}
```
3. **Error Handling**
```vue
<PrintDesigner @template-error="handleError" @print-error="handlePrintError" />
```
- **Silent Printing**: Add support for direct-to-printer functionality without user interaction, ideal for batch processing and automated workflows.
- **More Element Types**: Introduce new elements like charts.
- **Advanced Styling**: Provide more granular control over element styling and layout.
- **Improved Performance**: Continuously optimize performance for large and complex templates.
MIT License