HTML в PDF или изображение (JPEG, PNG, WEBP) конвертер через Chrome/Chromium.
npm install --save html-pdf-chromeЭта библиотека не предназначена для приема ненадежного пользовательского ввода. Это может иметь серьезные риски безопасности, такие как подделку запросов на стороне сервера (SSRF).
Если вы столкнетесь с проблемами CORS, попробуйте использовать хромированный флаг --disable-web-security , либо при запуске хромирования извне или в options.chromeFlags . Эта опция должна использоваться только в том случае, если вы полностью доверяете коду, который вы выполняете во время печатной работы!
Примечание: настоятельно рекомендуется сохранить хромированные бок с Node.js. Существует значительный накладной удар, запускающий хром для каждой генерации PDF, которого можно легко избежать.
Предполагается использовать PM2, чтобы гарантировать, что Chrome продолжает работать. Если он сбой, он перезагрузится автоматически.
На момент написания этой статьи, без головы Chrome использует около 65 МБ оперативной памяти во время холостого хода.
# 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.Машинопись:
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 ( ) ) ;Просмотреть полную документацию в исходном коде.
По умолчанию страницы сохраняются как PDF. Чтобы сохранить в качестве скриншота вместо этого, поставьте screenshotOptions . Все поддерживаемые параметры можно просмотреть здесь.
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 ) ;Мопс (ранее известный как нефрит)
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 ) ; Укажите дополнительные заголовки, которые вы хотите отправить с помощью вашего запроса через 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 ) ;Примечание: требуется хром 65 или более поздней версии.
По желанию вы можете предоставить шаблон HTML для пользовательского заголовка и/или нижнего колонтитула.
Несколько классов могут быть использованы для введения значений печати:
date - Отформатированная дата печатиtitle - Название документаurl - расположение документаpageNumber - номер текущего номера страницыtotalPages - общие страницы в документе Вы можете настроить поля с помощью printOptions marginTop , marginBottom , marginLeft и marginRight .
В настоящее время вы должны внедрить любые изображения, используя кодирование BASE64.
Вы можете просмотреть, как хром излагает шаблоны здесь.
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>' ,
} ,
} ) ; Есть несколько типов CompletionTrigger , которые ждут, пока что -то произойдет, прежде чем запустить 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-CHROME выпускается по лицензии MIT.