크롬/크롬을 통한 HTML에서 PDF 또는 이미지 (JPEG, PNG, WEBP) 변환기.
npm install --save html-pdf-chrome이 라이브러리는 신뢰할 수없는 사용자 입력을 수락하기위한 것이 아닙니다 . 그렇게하면 서버 측 요청 위조 (SSRF)와 같은 심각한 보안 위험이있을 수 있습니다.
CORS 문제가 발생하는 경우 크롬 외부 또는 options.chromeFlags 에서 크롬을 시작할 때 --disable-web-security chrome 플래그를 사용해보십시오. 이 옵션은 인쇄 작업 중에 실행중인 코드를 완전히 신뢰하는 경우에만 사용해야합니다!
참고 : Chrome을 Node.js로 나란히 실행하는 것이 좋습니다. 쉽게 피할 수있는 각 PDF 생성에 대해 크롬을 시작하는 상당한 오버 헤드가 있습니다.
크롬이 계속 실행되도록 PM2를 사용하는 것이 좋습니다. 충돌하면 자동으로 다시 시작됩니다.
이 글을 쓰는 시점에서 헤드리스 크롬은 유휴 상태에서 약 65MB의 RAM을 사용합니다.
# 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.TypeScript :
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 ( ) ) ;자바 스크립트 :
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 ) ;퍼그 (이전에 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 ) ; 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 ) ;참고 : Chrome 65 이상이 필요합니다.
선택적으로 사용자 정의 헤더 및/또는 바닥 글에 대한 HTML 템플릿을 제공 할 수 있습니다.
몇 가지 클래스를 사용하여 인쇄 값을 주입 할 수 있습니다.
date - 형식 인쇄 날짜title - 문서 제목url 문서 위치pageNumber 현재 페이지 번호totalPages 문서의 총 페이지 marginTop , marginBottom , marginLeft 및 marginRight 의 printOptions 로 마진을 조정할 수 있습니다.
현재 Base64 인코딩을 사용하여 이미지를 인화해야합니다.
Chrome이 여기에 템플릿을 어떻게 배치하는지 볼 수 있습니다.
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>' ,
} ,
} ) ; PDF 인쇄를 트리거하기 전에 무언가가 발생할 때까지 기다리는 몇 가지 CompletionTrigger 유형이 있습니다.
true 로 설정되기를 기다립니다.htmlPdf.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 라이센스에 따라 릴리스됩니다.