react-pdf-levelup 3.3.3 → 3.4.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 +5 -350
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
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
|
+
|
|
1
5
|
<p align="center">
|
|
2
6
|
<img src="https://genarogg.github.io/media/react-pdf-levelup/logo-de-react-pdf-levelup.png" alt="react-pdf-levelup logo" width="160" />
|
|
3
7
|
</p>
|
|
@@ -6,353 +10,4 @@
|
|
|
6
10
|
<strong style="color: red">📢 Esta librería ha cambiado de nombre a
|
|
7
11
|
|
|
8
12
|
<a href="https://www.npmjs.com/package/@react-pdf-levelup/core">@react-pdf-levelup/core</a></strong>
|
|
9
|
-
</h1>
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
# react-pdf-levelup
|
|
13
|
-
|
|
14
|
-
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.
|
|
15
|
-
|
|
16
|
-
# 🌐 **Playground en vivo:**
|
|
17
|
-
|
|
18
|
-
[https://react-pdf-levelup.nimbux.cloud](https://react-pdf-levelup.nimbux.cloud)
|
|
19
|
-
or
|
|
20
|
-
[https://react-pdf-levelup.nimbux.cloud](https://react-pdf-levelup.nimbux.cloud)
|
|
21
|
-
|
|
22
|
-
## 📦 Instalación
|
|
23
|
-
|
|
24
|
-
```bash
|
|
25
|
-
npm install react-pdf-levelup
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
## 🚀 Características
|
|
29
|
-
|
|
30
|
-
- 🧱 Construye PDFs con componentes de React usando los componentes de `react-pdf-levelup` (LayoutPDF, texto, listas, QR, tablas, columnas, etc.)
|
|
31
|
-
- 🖼 Vista previa en tiempo real de los documentos generados
|
|
32
|
-
- 🎨 Editor en vivo con Monaco Editor para personalizar código JSX
|
|
33
|
-
- 📦 Plantillas predefinidas listas para usar
|
|
34
|
-
- 📄 Soporte para códigos QR, tablas, imágenes, listas, layout dinámico, etc.
|
|
35
|
-
- 🔄 Generación de PDFs desde templates de React
|
|
36
|
-
- 📥 Descarga automática y vista previa de PDFs generados
|
|
37
|
-
|
|
38
|
-
## 📋 Funciones Principales
|
|
39
|
-
|
|
40
|
-
### `generatePDF`
|
|
41
|
-
|
|
42
|
-
Genera un PDF en formato base64 a partir de un componente de React.
|
|
43
|
-
|
|
44
|
-
```typescript
|
|
45
|
-
import { generatePDF } from "react-pdf-levelup";
|
|
46
|
-
|
|
47
|
-
const pdfBase64 = await generatePDF({
|
|
48
|
-
template: MyPDFTemplate,
|
|
49
|
-
data: {
|
|
50
|
-
title: "Mi Documento",
|
|
51
|
-
items: ["Item 1", "Item 2", "Item 3"],
|
|
52
|
-
},
|
|
53
|
-
});
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
**Parámetros:**
|
|
57
|
-
|
|
58
|
-
- `template`: Componente de React que define la estructura del PDF
|
|
59
|
-
- `data`: Datos opcionales que se pasarán al template
|
|
60
|
-
|
|
61
|
-
**Retorna:** Promise que resuelve a un string en base64 del PDF generado
|
|
62
|
-
|
|
63
|
-
### `decodeBase64Pdf`
|
|
64
|
-
|
|
65
|
-
Decodifica un PDF en base64 y permite descargarlo o abrirlo en una nueva pestaña.
|
|
66
|
-
|
|
67
|
-
```typescript
|
|
68
|
-
import { decodeBase64Pdf } from "react-pdf-levelup";
|
|
69
|
-
|
|
70
|
-
// Después de generar el PDF
|
|
71
|
-
const pdfBase64 = await generatePDF({ template: MyTemplate });
|
|
72
|
-
|
|
73
|
-
// Descargar y abrir el PDF
|
|
74
|
-
decodeBase64Pdf(pdfBase64, "mi-documento.pdf");
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
**Parámetros:**
|
|
78
|
-
|
|
79
|
-
- `base64`: String del PDF en formato base64
|
|
80
|
-
- `fileName`: Nombre del archivo para la descarga
|
|
81
|
-
|
|
82
|
-
**Funcionalidad:**
|
|
83
|
-
|
|
84
|
-
- Descarga automática del archivo PDF
|
|
85
|
-
- Abre el PDF en una nueva pestaña del navegador
|
|
86
|
-
- Limpia automáticamente los recursos de memoria
|
|
87
|
-
|
|
88
|
-
## 💡 Ejemplo de Uso con componentes levelup
|
|
89
|
-
|
|
90
|
-
```typescript
|
|
91
|
-
import React from 'react';
|
|
92
|
-
import { generatePDF, decodeBase64Pdf, LayoutPDF, H1, P, Strong, Em, HR, Container, Row, Col6, UL, LI, QR, Table, Thead, Tbody, Tr, Th, Td } from 'react-pdf-levelup';
|
|
93
|
-
|
|
94
|
-
const MyPDFTemplate = ({ data }) => (
|
|
95
|
-
<LayoutPDF>
|
|
96
|
-
<H1>Documento de Presentación</H1>
|
|
97
|
-
<P>
|
|
98
|
-
Bienvenido a <Strong>react-pdf-levelup</Strong>. Construye PDFs con componentes de React de forma <Em>rápida</Em> y <Em>tipada</Em>.
|
|
99
|
-
</P>
|
|
100
|
-
<HR />
|
|
101
|
-
<Container>
|
|
102
|
-
<Row>
|
|
103
|
-
<Col6>
|
|
104
|
-
<UL>
|
|
105
|
-
<LI>Plantillas listas</LI>
|
|
106
|
-
<LI>Componentes composables</LI>
|
|
107
|
-
<LI>TypeScript</LI>
|
|
108
|
-
<LI>Integración moderna</LI>
|
|
109
|
-
</UL>
|
|
110
|
-
</Col6>
|
|
111
|
-
<Col6>
|
|
112
|
-
<QR value="https://react-pdf-levelup.nimbux.cloud" size={120} />
|
|
113
|
-
</Col6>
|
|
114
|
-
</Row>
|
|
115
|
-
</Container>
|
|
116
|
-
<Table cellHeight={24}>
|
|
117
|
-
<Thead>
|
|
118
|
-
<Tr>
|
|
119
|
-
<Th width="40%">Producto</Th>
|
|
120
|
-
<Th width="20%">Cantidad</Th>
|
|
121
|
-
<Th width="20%">Precio</Th>
|
|
122
|
-
<Th width="20%">Total</Th>
|
|
123
|
-
</Tr>
|
|
124
|
-
</Thead>
|
|
125
|
-
<Tbody>
|
|
126
|
-
<Tr>
|
|
127
|
-
<Td width="40%">Etiqueta Térmica 50x30</Td>
|
|
128
|
-
<Td width="20%">2</Td>
|
|
129
|
-
<Td width="20%">$5.00</Td>
|
|
130
|
-
<Td width="20%">$10.00</Td>
|
|
131
|
-
</Tr>
|
|
132
|
-
</Tbody>
|
|
133
|
-
</Table>
|
|
134
|
-
</LayoutPDF>
|
|
135
|
-
);
|
|
136
|
-
|
|
137
|
-
// Función para generar y descargar PDF
|
|
138
|
-
const handleGeneratePDF = async () => {
|
|
139
|
-
try {
|
|
140
|
-
const pdfBase64 = await generatePDF({
|
|
141
|
-
template: MyPDFTemplate,
|
|
142
|
-
data: {
|
|
143
|
-
title: 'Mi Lista de Tareas',
|
|
144
|
-
items: [
|
|
145
|
-
'Revisar documentación',
|
|
146
|
-
'Implementar nuevas funciones',
|
|
147
|
-
'Realizar pruebas',
|
|
148
|
-
'Desplegar a producción'
|
|
149
|
-
]
|
|
150
|
-
}
|
|
151
|
-
});
|
|
152
|
-
|
|
153
|
-
// Descargar y abrir el PDF
|
|
154
|
-
decodeBase64Pdf(pdfBase64, 'lista-tareas.pdf');
|
|
155
|
-
|
|
156
|
-
} catch (error) {
|
|
157
|
-
console.error('Error generando PDF:', error);
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
|
|
161
|
-
// Componente React
|
|
162
|
-
const App = () => {
|
|
163
|
-
return (
|
|
164
|
-
<div>
|
|
165
|
-
<h1>Generador de PDF</h1>
|
|
166
|
-
<button onClick={handleGeneratePDF}>
|
|
167
|
-
Generar y Descargar PDF
|
|
168
|
-
</button>
|
|
169
|
-
</div>
|
|
170
|
-
);
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
export default App;
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
## 🎨 Templates Avanzados
|
|
177
|
-
|
|
178
|
-
```typescript
|
|
179
|
-
import { StyleSheet, Font } from '@react-pdf/renderer';
|
|
180
|
-
|
|
181
|
-
// Ejemplo de template para factura
|
|
182
|
-
const InvoiceTemplate = ({ data }) => (
|
|
183
|
-
<Document>
|
|
184
|
-
<Page size="A4" style={styles.page}>
|
|
185
|
-
<View style={styles.header}>
|
|
186
|
-
<Text style={styles.companyName}>{data.company}</Text>
|
|
187
|
-
<Text>Factura #{data.invoiceNumber}</Text>
|
|
188
|
-
</View>
|
|
189
|
-
|
|
190
|
-
<View style={styles.customerInfo}>
|
|
191
|
-
<Text>Cliente: {data.customer.name}</Text>
|
|
192
|
-
<Text>Email: {data.customer.email}</Text>
|
|
193
|
-
</View>
|
|
194
|
-
|
|
195
|
-
<View style={styles.itemsTable}>
|
|
196
|
-
{data.items.map((item, index) => (
|
|
197
|
-
<View key={index} style={styles.tableRow}>
|
|
198
|
-
<Text style={styles.itemName}>{item.name}</Text>
|
|
199
|
-
<Text style={styles.itemQuantity}>{item.quantity}</Text>
|
|
200
|
-
<Text style={styles.itemPrice}>${item.price}</Text>
|
|
201
|
-
</View>
|
|
202
|
-
))}
|
|
203
|
-
</View>
|
|
204
|
-
|
|
205
|
-
<View style={styles.total}>
|
|
206
|
-
<Text>Total: ${data.total}</Text>
|
|
207
|
-
</View>
|
|
208
|
-
</Page>
|
|
209
|
-
</Document>
|
|
210
|
-
);
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
## 🔧 Configuración Avanzada
|
|
214
|
-
|
|
215
|
-
### Manejo de Errores
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
const handlePDFGeneration = async () => {
|
|
219
|
-
try {
|
|
220
|
-
const pdfBase64 = await generatePDF({
|
|
221
|
-
template: MyTemplate,
|
|
222
|
-
data: myData,
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
decodeBase64Pdf(pdfBase64, "documento.pdf");
|
|
226
|
-
} catch (error) {
|
|
227
|
-
if (error.message.includes("Template not provided")) {
|
|
228
|
-
console.error("Error: No se proporcionó un template válido");
|
|
229
|
-
} else {
|
|
230
|
-
console.error("Error inesperado:", error.message);
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
};
|
|
234
|
-
```
|
|
235
|
-
|
|
236
|
-
### Solo Generar Base64 (sin descargar)
|
|
237
|
-
|
|
238
|
-
```typescript
|
|
239
|
-
const generatePDFOnly = async () => {
|
|
240
|
-
const pdfBase64 = await generatePDF({
|
|
241
|
-
template: MyTemplate,
|
|
242
|
-
data: myData,
|
|
243
|
-
});
|
|
244
|
-
|
|
245
|
-
// Usar el base64 para otros propósitos (envío por API, almacenamiento, etc.)
|
|
246
|
-
console.log("PDF generado:", pdfBase64);
|
|
247
|
-
return pdfBase64;
|
|
248
|
-
};
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
## 🛠 Dependencias
|
|
252
|
-
|
|
253
|
-
Esta librería utiliza internamente:
|
|
254
|
-
|
|
255
|
-
- `@react-pdf/renderer` - Para la generación de PDFs
|
|
256
|
-
- `react` - Para los componentes JSX
|
|
257
|
-
|
|
258
|
-
## 📝 Notas Importantes
|
|
259
|
-
|
|
260
|
-
- La función `decodeBase64Pdf` solo funciona en contexto de navegador (requiere `document`)
|
|
261
|
-
- Los templates deben usar los componentes de `react-pdf-levelup` y retornar JSX válido
|
|
262
|
-
- El PDF se genera de forma asíncrona, asegúrate de usar `await` o `.then()`
|
|
263
|
-
- Los recursos de memoria se limpian automáticamente después de la descarga
|
|
264
|
-
|
|
265
|
-
## 🌐 API REST para generar PDFs
|
|
266
|
-
|
|
267
|
-
- Genera PDFs vía HTTP desde cualquier lenguaje usando un template TSX en base64 y un objeto de datos.
|
|
268
|
-
- Devuelve un JSON con `data.pdf` que es el PDF en base64.
|
|
269
|
-
|
|
270
|
-
### Endpoints
|
|
271
|
-
|
|
272
|
-
- Cloud: [https://react-pdf-levelup.nimbux.cloud/api](https://react-pdf-levelup.nimbux.cloud/api)
|
|
273
|
-
- Auto‑hospedado ZIP: [https://genarogg.github.io/react-pdf-levelup/public/api.zip](https://genarogg.github.io/react-pdf-levelup/public/api.zip)
|
|
274
|
-
|
|
275
|
-
```text
|
|
276
|
-
https://react-pdf-levelup.nimbux.cloud/api
|
|
277
|
-
```
|
|
278
|
-
|
|
279
|
-
```text
|
|
280
|
-
https://genarogg.github.io/react-pdf-levelup/public/api.zip
|
|
281
|
-
```
|
|
282
|
-
|
|
283
|
-
### Request
|
|
284
|
-
|
|
285
|
-
POST con `Content-Type: application/json`:
|
|
286
|
-
|
|
287
|
-
```json
|
|
288
|
-
{
|
|
289
|
-
"template": "<TSX_EN_BASE64>",
|
|
290
|
-
"data": { "campo": "valor" }
|
|
291
|
-
}
|
|
292
|
-
```
|
|
293
|
-
|
|
294
|
-
### Response
|
|
295
|
-
|
|
296
|
-
```json
|
|
297
|
-
{
|
|
298
|
-
"data": {
|
|
299
|
-
"pdf": "<PDF_EN_BASE64>"
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
```
|
|
303
|
-
|
|
304
|
-
### Ejemplo rápido con Node.js (fetch)
|
|
305
|
-
|
|
306
|
-
```ts
|
|
307
|
-
import fs from "fs";
|
|
308
|
-
import path from "path";
|
|
309
|
-
|
|
310
|
-
type ApiResponse = { data?: { pdf?: string } };
|
|
311
|
-
const ENDPOINT_API = "https://react-pdf-levelup.nimbux.cloud/api";
|
|
312
|
-
|
|
313
|
-
const petition = async ({
|
|
314
|
-
template,
|
|
315
|
-
data,
|
|
316
|
-
}: {
|
|
317
|
-
template: string;
|
|
318
|
-
data: any;
|
|
319
|
-
}): Promise<string> => {
|
|
320
|
-
const templatePath = path.join(process.cwd(), "src", "useExample", template);
|
|
321
|
-
const tsxCode = fs.readFileSync(templatePath, "utf-8");
|
|
322
|
-
const templateBase64 = Buffer.from(tsxCode, "utf-8").toString("base64");
|
|
323
|
-
|
|
324
|
-
const res = await fetch(ENDPOINT_API, {
|
|
325
|
-
method: "POST",
|
|
326
|
-
headers: { "Content-Type": "application/json" },
|
|
327
|
-
body: JSON.stringify({ template: templateBase64, data }),
|
|
328
|
-
});
|
|
329
|
-
if (!res.ok)
|
|
330
|
-
throw new Error(`API error (${res.status}): ${await res.text()}`);
|
|
331
|
-
const json = (await res.json()) as ApiResponse;
|
|
332
|
-
return json?.data?.pdf ?? "";
|
|
333
|
-
};
|
|
334
|
-
|
|
335
|
-
const savePDF = (base64: string) => {
|
|
336
|
-
const buffer = Buffer.from(base64, "base64");
|
|
337
|
-
const outputPath = path.join(process.cwd(), "example.pdf");
|
|
338
|
-
fs.writeFileSync(outputPath, buffer);
|
|
339
|
-
console.log("PDF guardado:", outputPath);
|
|
340
|
-
};
|
|
341
|
-
```
|
|
342
|
-
|
|
343
|
-
### Self‑hosting propio
|
|
344
|
-
|
|
345
|
-
- Descarga el paquete ZIP y despliega en tu infraestructura (Node/Docker/PaaS).
|
|
346
|
-
- Expón el endpoint `/api/pdf` con el mismo contrato JSON.
|
|
347
|
-
- Usa el mismo cliente mostrado arriba apuntando a tu URL.
|
|
348
|
-
|
|
349
|
-
Más detalles y ejemplos en la documentación:
|
|
350
|
-
[Guía API REST (fetch)](https://react-pdf-levelup-docs.nimbux.cloud/docs/guides/api-rest)
|
|
351
|
-
|
|
352
|
-
## 🤝 Contribuir
|
|
353
|
-
|
|
354
|
-
Las contribuciones son bienvenidas. Por favor, abre un issue o envía un pull request.
|
|
355
|
-
|
|
356
|
-
## 📄 Licencia
|
|
357
|
-
|
|
358
|
-
MIT License
|
|
13
|
+
</h1>
|