Convertir HTML a PDF profesional con Puppeteer y wkhtmltopdf
Existen dos herramientas principales para convertir HTML a PDF de calidad profesional en Windows: Puppeteer (usa Chromium headless, ideal para documentos con CSS moderno y fuentes web) y wkhtmltopdf (binario standalone, sin Node.js).
Puppeteer: la opción más potente
Instalar Puppeteer
npm install puppeteer
# O la versión ligera que usa Chrome del sistema:
npm install puppeteer-core
Script completo de conversión HTML → PDF
const puppeteer = require('puppeteer');
async function convertirAPDF(opciones = {}) {
const {
html, // string HTML o ruta de archivo
salida, // ruta del PDF de salida
formato = 'A4',
orientacion = 'portrait',
margen = { top:'15mm', bottom:'15mm', left:'15mm', right:'15mm' },
cabecera = '', // HTML del encabezado (nº página, fecha)
pie = '' // HTML del pie de página
} = opciones;
const browser = await puppeteer.launch({ headless: 'new' });
const page = await browser.newPage();
// Cargar desde string HTML o desde URL/ruta
if (html.startsWith('http') || html.endsWith('.html')) {
await page.goto('file:///' + html.replace(/\\/g, '/'), { waitUntil: 'networkidle0' });
} else {
await page.setContent(html, { waitUntil: 'networkidle0' });
}
await page.pdf({
path: salida,
format: formato,
landscape: orientacion === 'landscape',
margin: margen,
printBackground: true,
displayHeaderFooter: !!(cabecera || pie),
headerTemplate: cabecera || '<span></span>',
footerTemplate: pie || `
<div style="font-size:9px; width:100%; text-align:center; color:#888; padding:5px">
Página <span class="pageNumber"></span> de <span class="totalPages"></span>
</div>`
});
await browser.close();
return salida;
}
wkhtmltopdf: sin Node.js
Instalar y convertir
# Instalar con Chocolatey
choco install wkhtmltopdf -y
# Conversión básica
wkhtmltopdf documento.html documento.pdf
# Con cabecera, pie y opciones A4
wkhtmltopdf `
--page-size A4 `
--margin-top 15mm --margin-bottom 20mm `
--header-html cabecera.html `
--footer-center "Página [page] de [toPage]" `
--footer-font-size 9 `
documento.html documento.pdf
Generar lote de PDFs desde Cerewro
Convertir toda una carpeta de HTMLs
Convierte todos los archivos HTML de C:\facturas\2026\html\ a PDF y guárdalos en C:\facturas\2026\pdf\
| Puppeteer | wkhtmltopdf | |
|---|---|---|
| CSS moderno | ✅ Perfecto (Chromium) | ⚠️ Limitado |
| Fuentes web (@font-face) | ✅ Sí | ⚠️ Parcial |
| Requiere Node.js | Sí | No |
| Velocidad | Media | Rápida |
| Tamaño instalación | ~300 MB (Chromium) | ~50 MB |