HTML a PDF o convertidor de imagen (JPEG, PNG, WebP) a través de Chrome/Chromium.
npm install --save html-pdf-chromeEsta biblioteca no está destinada a aceptar la entrada del usuario no confiable. Hacerlo puede tener graves riesgos de seguridad, como falsificación de solicitud del lado del servidor (SSRF).
Si se encuentra con problemas de CORS, intente usar el indicador de Chrome -Security --disable-web-security , ya sea cuando comience a Chrome externamente o en options.chromeFlags . ¡Esta opción solo debe usarse si confía completamente en el código que está ejecutando durante un trabajo de impresión!
Nota: Se recomienda encarecidamente que mantenga a Chrome corriendo de lado a lado con Node.js. Existe una cromo inicial significativa para cada generación de PDF que se puede evitar fácilmente.
Se sugiere usar PM2 para garantizar que Chrome continúe funcionando. Si se bloquea, se reiniciará automáticamente.
Al momento de escribir este artículo, Chrome sin cabeza usa aproximadamente 65 MB de RAM mientras está inactivo.
# install pm2 globally
npm install -g pm2
# start Chrome and be sure to specify a port to use in the html-pdf-chrome options.
pm2 start google-chrome
--interpreter none
--
--headless
--disable-gpu
--disable-translate
--disable-extensions
--disable-background-networking
--safebrowsing-disable-auto-update
--disable-sync
--metrics-recording-only
--disable-default-apps
--no-first-run
--mute-audio
--hide-scrollbars
--remote-debugging-port= < port goes here >
# run your Node.js app.Mecanografiado:
import * as htmlPdf from 'html-pdf-chrome' ;
const html = '<p>Hello, world!</p>' ;
const options : htmlPdf . CreateOptions = {
port : 9222 , // port Chrome is listening on
} ;
// async
const pdf = await htmlPdf . create ( html , options ) ;
await pdf . toFile ( 'test.pdf' ) ;
const base64 = pdf . toBase64 ( ) ;
const buffer = pdf . toBuffer ( ) ;
const stream = pdf . toStream ( ) ;
// Promise
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toFile ( 'test.pdf' ) ) ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toBase64 ( ) ) ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toBuffer ( ) ) ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toStream ( ) ) ;JavaScript:
const htmlPdf = require ( 'html-pdf-chrome' ) ;
const html = '<p>Hello, world!</p>' ;
const options = {
port : 9222 , // port Chrome is listening on
} ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toFile ( 'test.pdf' ) ) ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toBase64 ( ) ) ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toBuffer ( ) ) ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toStream ( ) ) ;Vea la documentación completa en el código fuente.
Por defecto, las páginas se guardan como PDF. Para ahorrar como captura de pantalla, suministre screenshotOptions . Todas las opciones compatibles se pueden ver aquí.
const htmlPdf = require ( 'html-pdf-chrome' ) ;
const html = '<p>Hello, world!</p>' ;
const options = {
port : 9222 , // port Chrome is listening on
screenshotOptions : {
format : 'png' , // png, jpeg, or webp. Optional, defaults to png.
// quality: 100, // Optional, quality percent (jpeg only)
// optional, defaults to entire window
clip : {
x : 0 ,
y : 0 ,
width : 100 ,
height : 200 ,
scale : 1 ,
} ,
} ,
// Optional. Options here: https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setDeviceMetricsOverride
deviceMetrics : {
width : 1000 ,
height : 1000 ,
deviceScaleFactor : 0 ,
mobile : false ,
} ,
} ;
htmlPdf . create ( html , options ) . then ( ( pdf ) => pdf . toFile ( 'test.png' ) ) ; import * as htmlPdf from 'html-pdf-chrome' ;
const options : htmlPdf . CreateOptions = {
port : 9222 , // port Chrome is listening on
} ;
const url = 'https://github.com/westy92/html-pdf-chrome' ;
const pdf = await htmlPdf . create ( url , options ) ; import * as htmlPdf from 'html-pdf-chrome' ;
import * as marked from 'marked' ;
const options : htmlPdf . CreateOptions = {
port : 9222 , // port Chrome is listening on
} ;
const html = marked ( '# Hello [World](https://www.google.com/)!' ) ;
const pdf = await htmlPdf . create ( html , options ) ;Pug (anteriormente conocido como Jade)
import * as htmlPdf from 'html-pdf-chrome' ;
import * as pug from 'pug' ;
const template = pug . compile ( 'p Hello, #{noun}!' ) ;
const templateData = {
noun : 'world' ,
} ;
const options : htmlPdf . CreateOptions = {
port : 9222 , // port Chrome is listening on
} ;
const html = template ( templateData ) ;
const pdf = await htmlPdf . create ( html , options ) ; Especifique encabezados adicionales que desee enviar con su solicitud a través de CreateOptions.extraHTTPHeaders .
const options : HtmlPdf . CreateOptions = {
port : 9222 , // port Chrome is listening on
extraHTTPHeaders : {
'Authorization' : 'Bearer 123' ,
'X-Custom-Test-Header' : 'This is great!' ,
} ,
} ;
const pdf = await HtmlPdf . create ( 'https://httpbin.org/headers' , options ) ;Nota: requiere Chrome 65 o posterior.
Opcionalmente, puede proporcionar una plantilla HTML para un encabezado y/o pie de página personalizado.
Se pueden usar algunas clases para inyectar valores de impresión:
date - Fecha de impresión formateadatitle - Título del documentourl - Ubicación del documentopageNumber - Número de página actualtotalPages - Páginas totales en el documento Puede ajustar los márgenes con las printOptions de marginTop , marginBottom , marginLeft y marginRight .
En este momento, debe en línea cualquier imagen utilizando la codificación Base64.
Puede ver cómo Chrome establece las plantillas aquí.
const pdf = await htmlPdf . create ( html , {
port ,
printOptions : {
displayHeaderFooter : true ,
headerTemplate : `
<div class="text center">
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>
` ,
footerTemplate : '<div class="text center">Custom footer!</div>' ,
} ,
} ) ; Hay algunos tipos CompletionTrigger que esperan que ocurra algo antes de activar la impresión de PDF.
truehtmlPdf.CompletionTrigger.CompletionTrigger const options : htmlPdf . CreateOptions = {
port : 9222 , // port Chrome is listening on
completionTrigger : new htmlPdf . CompletionTrigger . Timer ( 5000 ) , // milliseconds
} ;
// Alternative completionTrigger options:
new htmlPdf . CompletionTrigger . Callback (
'cbName' , // optional, name of the callback to define for the browser to call when finished rendering. Defaults to 'htmlPdfCb'.
5000 // optional, timeout (milliseconds)
) ,
new htmlPdf . CompletionTrigger . Element (
'div#myElement' , // name of the DOM element to wait for
5000 // optional, timeout (milliseconds)
) ,
new htmlPdf . CompletionTrigger . Event (
'myEvent' , // name of the event to listen for
'#myElement' , // optional DOM element CSS selector to listen on, defaults to body
5000 // optional timeout (milliseconds)
) ,
new htmlPdf . CompletionTrigger . LifecycleEvent (
'networkIdle' , // name of the Chrome lifecycle event to listen for. Defaults to 'firstMeaningfulPaint'.
5000 // optional timeout (milliseconds)
) ,
new htmlPdf . CompletionTrigger . Variable (
'myVarName' , // optional, name of the variable to wait for. Defaults to 'htmlPdfDone'
5000 // optional, timeout (milliseconds)
) , HTML-PDF-CROME se libera bajo la licencia MIT.