-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
276 lines (242 loc) · 10 KB
/
Copy pathserver.js
File metadata and controls
276 lines (242 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* ============================================================
* WiDocs — PDF Generation API
* ============================================================
* POST /api/generate-pdf
*
* Body (JSON):
* - content : string — Markdown text to render
* - background: string — URL or data-URI (Base64) of the background image
*
* Response: application/pdf (binary stream)
* ============================================================
*/
const express = require('express');
const cors = require('cors');
const puppeteer = require('puppeteer');
const MarkdownIt = require('markdown-it');
// ── Markdown-it setup ──────────────────────────────────────
const md = new MarkdownIt({
html: true, // Allow raw HTML inside Markdown
linkify: true, // Auto-convert URL-like text to links
typographer: true, // Enable smart quotes & other typographic niceties
breaks: true, // Convert \n in paragraphs into <br>
});
// ── Express setup ──────────────────────────────────────────
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json({ limit: '50mb' })); // Large payloads (Base64 images)
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// ── Health-check ───────────────────────────────────────────
app.get('/', (_req, res) => {
res.json({
service: 'WiDocs PDF API',
status: 'running',
version: '1.0.0',
endpoint: 'POST /api/generate-pdf',
});
});
// ── PDF Generation Endpoint ────────────────────────────────
app.post('/api/generate-pdf', async (req, res) => {
const {
content,
background,
isHtml,
marginTop = 40,
marginBottom = 30,
marginX = 25,
paperWidth = 210,
paperHeight = 297,
pageColor = '#ffffff',
contentColor = '#ffffff',
fontSize = 12
} = req.body;
if (!content || !background) {
return res.status(400).json({ error: 'Faltan campos obligatorios (content y background).' });
}
let browser;
try {
// If content is an array, it's already paginated HTML strings from the client
const pagesToRender = Array.isArray(content) ? content : md.render(content);
const fullHtml = buildHtmlDocument(pagesToRender, background, marginTop, marginBottom, marginX, paperWidth, paperHeight, pageColor, contentColor, fontSize);
console.log('[WiDocs] Launching Puppeteer...');
browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu']
});
const page = await browser.newPage();
await page.setContent(fullHtml, { waitUntil: 'networkidle0', timeout: 120000 });
// Small delay to ensure all styles/images are fully rendered
await new Promise(r => setTimeout(r, 500));
const pdfBuffer = await page.pdf({
width: `${paperWidth}mm`,
height: `${paperHeight}mm`,
margin: { top: '0mm', right: '0mm', bottom: '0mm', left: '0mm' },
printBackground: true,
});
await browser.close();
browser = null;
console.log(`[WiDocs] PDF generated OK — ${pdfBuffer.length} bytes`);
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="widocs.pdf"',
'Content-Length': pdfBuffer.length,
});
return res.end(Buffer.from(pdfBuffer));
} catch (err) {
console.error('[WiDocs] API Error:', err);
if (browser) await browser.close().catch(() => {});
return res.status(500).json({ error: 'Error al generar PDF', details: err.message });
}
});
// ── HTML/Normal Document Endpoint ──────────────────────────
app.post('/api/generate-html', async (req, res) => {
const { content, background, isHtml, marginTop, marginBottom, marginX, paperWidth, paperHeight, pageColor, contentColor, fontSize } = req.body;
try {
const htmlBody = isHtml ? content : md.render(content);
const fullHtml = buildHtmlDocument(htmlBody, background, marginTop, marginBottom, marginX, paperWidth, paperHeight, pageColor, contentColor, fontSize);
res.set({
'Content-Type': 'text/html',
'Content-Disposition': 'attachment; filename="widocs.html"',
});
return res.send(fullHtml);
} catch (err) {
return res.status(500).json({ error: 'Error al generar HTML', details: err.message });
}
});
// ── Word Document (.doc) Endpoint ──────────────────────────
app.post('/api/generate-docx', async (req, res) => {
const { content, background, isHtml, marginTop, marginBottom, marginX, paperWidth, paperHeight, pageColor, contentColor, fontSize } = req.body;
try {
const htmlBody = isHtml ? content : md.render(content);
const fullHtml = buildHtmlDocument(htmlBody, background, marginTop, marginBottom, marginX, paperWidth, paperHeight, pageColor, contentColor, fontSize);
res.set({
'Content-Type': 'application/msword',
'Content-Disposition': 'attachment; filename="widocs.doc"',
});
return res.send(fullHtml);
} catch (err) {
return res.status(500).json({ error: 'Error al generar Word', details: err.message });
}
});
// ── HTML Template Builder ──
function buildHtmlDocument(content, bgImage, marginTop = 40, marginBottom = 30, marginX = 25, paperWidth = 210, paperHeight = 297, pageColor = '#ffffff', contentColor = '#ffffff', fontSize = 12) {
// content can be a string (raw HTML) or an array of pages (each page can be a string or array of tags)
const pages = Array.isArray(content) ? content : [content];
return /* html */ `
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>WiDocs Document</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
@page { size: ${paperWidth}mm ${paperHeight}mm; margin: 0; }
html, body {
margin: 0;
padding: 0;
background: #f0f0f0;
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
box-sizing: border-box;
}
*, *:before, *:after { box-sizing: inherit; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
.page {
position: relative;
width: ${paperWidth}mm;
height: ${paperHeight}mm;
background-color: ${pageColor};
overflow: hidden;
page-break-after: always;
}
.page-background {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
background-image: url("${bgImage}");
background-size: cover;
background-position: center;
z-index: 1;
}
.page-content {
position: absolute;
top: ${marginTop}mm;
left: ${marginX}mm;
width: ${paperWidth - (marginX * 2)}mm;
height: ${paperHeight - marginTop - marginBottom}mm;
z-index: 2;
font-family: 'Inter', sans-serif;
font-size: ${fontSize}pt;
line-height: 1.6;
color: #1a1a2e;
background-color: ${contentColor};
}
/* Core Styles for Content */
.page-content h1, .page-content h2, .page-content h3 {
color: #0f0f23;
margin: 0;
line-height: 1.2;
padding: 0.2em 0;
}
.page-content h1 { font-size: 2em; }
.page-content h2 { font-size: 1.5em; }
.page-content h3 { font-size: 1.2em; }
.preview-content p, .page-content p { margin: 0; text-align: justify; line-height: 1.6; }
.preview-content ul, .preview-content ol, .page-content ul, .page-content ol { padding-left: 1.5em; margin: 0; }
.preview-content li, .page-content li { margin: 0; line-height: 1.6; }
.preview-content table, .page-content table {
width: 100%; border-collapse: collapse; margin: 0;
table-layout: fixed; font-size: 0.9em;
}
.page-content th, .page-content td {
border: 1px solid #d1d5db; padding: 4px 6px; word-wrap: break-word;
}
.page-content th { background: #6366f1; color: white; }
.page-content tr:nth-child(even) { background: rgba(99,102,241,0.03); }
pre, code {
background: transparent !important; color: inherit; padding: 0;
font-size: inherit; white-space: pre-wrap; word-break: break-all; margin: 0;
}
img { max-width: 100%; border-radius: 4px; display: block; margin: 1em auto; }
hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.5em 0; }
@media print {
body { background: transparent; }
.page { box-shadow: none; border: none; }
}
</style>
</head>
<body>
${pages.map(pageContent => {
// If pageContent is an array of tags, join them
const htmlSnippet = Array.isArray(pageContent) ? pageContent.join('') : pageContent;
return `
<div class="page">
<div class="page-background"></div>
<div class="page-content">
${htmlSnippet}
</div>
</div>
`;
}).join('')}
</body>
</html>`;
}
// ── Start server ───────────────────────────────────────────
app.listen(PORT, () => {
console.log(`
╔══════════════════════════════════════════╗
║ 🟢 WiDocs PDF API ║
║ 📍 http://localhost:${PORT} ║
║ 📄 POST /api/generate-pdf ║
╚══════════════════════════════════════════╝
`);
});