react-pdf-levelup 2.0.33 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,54 +1,244 @@
1
- # React + TypeScript + Vite
2
-
3
- This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
-
5
- Currently, two official plugins are available:
6
-
7
- - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
8
- - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
9
-
10
- ## Expanding the ESLint configuration
11
-
12
- If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
13
-
14
- ```js
15
- export default tseslint.config({
16
- extends: [
17
- // Remove ...tseslint.configs.recommended and replace with this
18
- ...tseslint.configs.recommendedTypeChecked,
19
- // Alternatively, use this for stricter rules
20
- ...tseslint.configs.strictTypeChecked,
21
- // Optionally, add this for stylistic rules
22
- ...tseslint.configs.stylisticTypeChecked,
23
- ],
24
- languageOptions: {
25
- // other options...
26
- parserOptions: {
27
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
28
- tsconfigRootDir: import.meta.dirname,
29
- },
30
- },
31
- })
1
+ # react-pdf-levelup
2
+
3
+ Generador de PDFs dinámicos con React. Esta herramienta te permite crear plantillas PDF con componentes JSX personalizados y previsualizarlas en tiempo real dentro de una aplicación web. Ideal para etiquetas, facturas, reportes, certificados, tablas y más.
4
+
5
+ # 🌐 **Playground en vivo:**
6
+ [https://react-pdf-levelup.netlify.app](https://react-pdf-levelup.netlify.app)
7
+
8
+ ## 📦 Instalación
9
+
10
+ ```bash
11
+ npm install react-pdf-levelup
12
+ ```
13
+
14
+ ## 🚀 Características
15
+
16
+ - 🧱 Construye PDFs con componentes de React usando `@react-pdf/renderer`
17
+ - 🖼 Vista previa en tiempo real de los documentos generados
18
+ - 🎨 Editor en vivo con Monaco Editor para personalizar código JSX
19
+ - 📦 Plantillas predefinidas listas para usar
20
+ - 📄 Soporte para códigos QR, tablas, imágenes, listas, layout dinámico, etc.
21
+ - 🔄 Generación de PDFs desde templates de React
22
+ - 📥 Descarga automática y vista previa de PDFs generados
23
+
24
+ ## 📋 Funciones Principales
25
+
26
+ ### `generatePDF`
27
+
28
+ Genera un PDF en formato base64 a partir de un componente de React.
29
+
30
+ ```typescript
31
+ import { generatePDF } from 'react-pdf-levelup';
32
+
33
+ const pdfBase64 = await generatePDF({
34
+ template: MyPDFTemplate,
35
+ data: {
36
+ title: 'Mi Documento',
37
+ items: ['Item 1', 'Item 2', 'Item 3']
38
+ }
39
+ });
40
+ ```
41
+
42
+ **Parámetros:**
43
+ - `template`: Componente de React que define la estructura del PDF
44
+ - `data`: Datos opcionales que se pasarán al template
45
+
46
+ **Retorna:** Promise que resuelve a un string en base64 del PDF generado
47
+
48
+ ### `decodeBase64Pdf`
49
+
50
+ Decodifica un PDF en base64 y permite descargarlo o abrirlo en una nueva pestaña.
51
+
52
+ ```typescript
53
+ import { decodeBase64Pdf } from 'react-pdf-levelup';
54
+
55
+ // Después de generar el PDF
56
+ const pdfBase64 = await generatePDF({ template: MyTemplate });
57
+
58
+ // Descargar y abrir el PDF
59
+ decodeBase64Pdf(pdfBase64, 'mi-documento.pdf');
32
60
  ```
33
61
 
34
- You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
62
+ **Parámetros:**
63
+ - `base64`: String del PDF en formato base64
64
+ - `fileName`: Nombre del archivo para la descarga
35
65
 
36
- ```js
37
- // eslint.config.js
38
- import reactX from 'eslint-plugin-react-x'
39
- import reactDom from 'eslint-plugin-react-dom'
66
+ **Funcionalidad:**
67
+ - Descarga automática del archivo PDF
68
+ - Abre el PDF en una nueva pestaña del navegador
69
+ - Limpia automáticamente los recursos de memoria
40
70
 
41
- export default tseslint.config({
42
- plugins: {
43
- // Add the react-x and react-dom plugins
44
- 'react-x': reactX,
45
- 'react-dom': reactDom,
71
+ ## 💡 Ejemplo de Uso Completo
72
+
73
+ ```typescript
74
+ import React from 'react';
75
+ import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
76
+ import { generatePDF, decodeBase64Pdf } from 'react-pdf-levelup';
77
+
78
+ // Definir estilos para el PDF
79
+ const styles = StyleSheet.create({
80
+ page: {
81
+ flexDirection: 'column',
82
+ backgroundColor: '#E4E4E4',
83
+ padding: 30,
84
+ },
85
+ section: {
86
+ margin: 10,
87
+ padding: 10,
88
+ flexGrow: 1,
46
89
  },
47
- rules: {
48
- // other rules...
49
- // Enable its recommended typescript rules
50
- ...reactX.configs['recommended-typescript'].rules,
51
- ...reactDom.configs.recommended.rules,
90
+ title: {
91
+ fontSize: 24,
92
+ marginBottom: 10,
52
93
  },
53
- })
94
+ });
95
+
96
+ // Crear template del PDF
97
+ const MyPDFTemplate = ({ data }) => (
98
+ <Document>
99
+ <Page size="A4" style={styles.page}>
100
+ <View style={styles.section}>
101
+ <Text style={styles.title}>{data?.title || 'Documento PDF'}</Text>
102
+ {data?.items?.map((item, index) => (
103
+ <Text key={index}>• {item}</Text>
104
+ ))}
105
+ </View>
106
+ </Page>
107
+ </Document>
108
+ );
109
+
110
+ // Función para generar y descargar PDF
111
+ const handleGeneratePDF = async () => {
112
+ try {
113
+ const pdfBase64 = await generatePDF({
114
+ template: MyPDFTemplate,
115
+ data: {
116
+ title: 'Mi Lista de Tareas',
117
+ items: [
118
+ 'Revisar documentación',
119
+ 'Implementar nuevas funciones',
120
+ 'Realizar pruebas',
121
+ 'Desplegar a producción'
122
+ ]
123
+ }
124
+ });
125
+
126
+ // Descargar y abrir el PDF
127
+ decodeBase64Pdf(pdfBase64, 'lista-tareas.pdf');
128
+
129
+ } catch (error) {
130
+ console.error('Error generando PDF:', error);
131
+ }
132
+ };
133
+
134
+ // Componente React
135
+ const App = () => {
136
+ return (
137
+ <div>
138
+ <h1>Generador de PDF</h1>
139
+ <button onClick={handleGeneratePDF}>
140
+ Generar y Descargar PDF
141
+ </button>
142
+ </div>
143
+ );
144
+ };
145
+
146
+ export default App;
147
+ ```
148
+
149
+ ## 🎨 Templates Avanzados
150
+
151
+ ```typescript
152
+ import { StyleSheet, Font } from '@react-pdf/renderer';
153
+
154
+ // Ejemplo de template para factura
155
+ const InvoiceTemplate = ({ data }) => (
156
+ <Document>
157
+ <Page size="A4" style={styles.page}>
158
+ <View style={styles.header}>
159
+ <Text style={styles.companyName}>{data.company}</Text>
160
+ <Text>Factura #{data.invoiceNumber}</Text>
161
+ </View>
162
+
163
+ <View style={styles.customerInfo}>
164
+ <Text>Cliente: {data.customer.name}</Text>
165
+ <Text>Email: {data.customer.email}</Text>
166
+ </View>
167
+
168
+ <View style={styles.itemsTable}>
169
+ {data.items.map((item, index) => (
170
+ <View key={index} style={styles.tableRow}>
171
+ <Text style={styles.itemName}>{item.name}</Text>
172
+ <Text style={styles.itemQuantity}>{item.quantity}</Text>
173
+ <Text style={styles.itemPrice}>${item.price}</Text>
174
+ </View>
175
+ ))}
176
+ </View>
177
+
178
+ <View style={styles.total}>
179
+ <Text>Total: ${data.total}</Text>
180
+ </View>
181
+ </Page>
182
+ </Document>
183
+ );
184
+ ```
185
+
186
+ ## 🔧 Configuración Avanzada
187
+
188
+ ### Manejo de Errores
189
+
190
+ ```typescript
191
+ const handlePDFGeneration = async () => {
192
+ try {
193
+ const pdfBase64 = await generatePDF({
194
+ template: MyTemplate,
195
+ data: myData
196
+ });
197
+
198
+ decodeBase64Pdf(pdfBase64, 'documento.pdf');
199
+
200
+ } catch (error) {
201
+ if (error.message.includes('Template not provided')) {
202
+ console.error('Error: No se proporcionó un template válido');
203
+ } else {
204
+ console.error('Error inesperado:', error.message);
205
+ }
206
+ }
207
+ };
54
208
  ```
209
+
210
+ ### Solo Generar Base64 (sin descargar)
211
+
212
+ ```typescript
213
+ const generatePDFOnly = async () => {
214
+ const pdfBase64 = await generatePDF({
215
+ template: MyTemplate,
216
+ data: myData
217
+ });
218
+
219
+ // Usar el base64 para otros propósitos (envío por API, almacenamiento, etc.)
220
+ console.log('PDF generado:', pdfBase64);
221
+ return pdfBase64;
222
+ };
223
+ ```
224
+
225
+ ## 🛠 Dependencias
226
+
227
+ Esta librería utiliza internamente:
228
+ - `@react-pdf/renderer` - Para la generación de PDFs
229
+ - `react` - Para los componentes JSX
230
+
231
+ ## 📝 Notas Importantes
232
+
233
+ - La función `decodeBase64Pdf` solo funciona en contexto de navegador (requiere `document`)
234
+ - Los templates deben ser componentes válidos de `@react-pdf/renderer`
235
+ - El PDF se genera de forma asíncrona, asegúrate de usar `await` o `.then()`
236
+ - Los recursos de memoria se limpian automáticamente después de la descarga
237
+
238
+ ## 🤝 Contribuir
239
+
240
+ Las contribuciones son bienvenidas. Por favor, abre un issue o envía un pull request.
241
+
242
+ ## 📄 Licencia
243
+
244
+ MIT License