HTML para PDF ou Image (conversor JPEG, PNG, WebP) via Chrome/Chromium.
npm install --save html-pdf-chromeEsta biblioteca não pretende aceitar a entrada do usuário não confiável. Isso pode ter riscos de segurança sérios, como falsificação de solicitação do servidor (SSRF).
Se você tiver problemas com o CORS, tente usar o sinalizador Chrome --disable-web-security , quando você inicia o Chrome externamente ou em options.chromeFlags . Esta opção deve ser usada apenas se você confiar totalmente no código que está executando durante um trabalho de impressão!
Nota: É altamente recomendável que você mantenha o Chrome funcionando lado a lado com o Node.JS. Existe uma sobrecarga significativa de cromo para cada geração em PDF que pode ser facilmente evitada.
Sugeriu -se usar o PM2 para garantir que o Chrome continue a ser executado. Se travar, será reiniciado automaticamente.
Até o momento em que este artigo foi escrito, o Chrome sem cabeça usa cerca de 65 MB de RAM enquanto ocioso.
# 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.Datilografado:
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 ( ) ) ;Veja a documentação completa no código -fonte.
Por padrão, as páginas são salvas como um PDF. Para salvar como captura de tela, suprimento screenshotOptions . Todas as opções suportadas podem ser visualizadas aqui.
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 conhecido 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 cabeçalhos adicionais que você deseja enviar com sua solicitação via 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: requer o Chrome 65 ou posterior.
Opcionalmente, você pode fornecer um modelo HTML para um cabeçalho e/ou rodapé personalizados.
Algumas classes podem ser usadas para injetar valores de impressão:
date - Data de impressão formatadatitle - Título do Documentourl - Localização do documentopageNumber - número atual da páginatotalPages - Páginas totais no documento Você pode ajustar as margens com as printOptions de marginTop , marginBottom , marginLeft e marginRight .
Neste momento, você deve embrulhar qualquer imagens usando a codificação Base64.
Você pode ver como o Chrome estabelece os modelos aqui.
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>' ,
} ,
} ) ; Existem alguns tipos CompletionTrigger que aguardam algo antes de desencadear a impressão em 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-CROMOM é liberado sob a licença do MIT.