Last active
April 26, 2024 23:19
-
-
Save monochromer/b80bc20c36b9e2f516a2af18a509845d to your computer and use it in GitHub Desktop.
Print pdf with headless chrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* chrome-remote-interface: JavaScript API, обеспечивающее простую абстракцию для команд и уведомлений | |
* | |
* chrome-launcher: позволяет нам запускать Chrome из Node.js кроссплаторменно | |
*/ | |
const chromeLauncher = require('chrome-launcher'); | |
const CDP = require('chrome-remote-interface'); | |
const file = require('fs'); | |
(async function() { | |
async function launchChrome() { | |
return await chromeLauncher.launch({ | |
chromeFlags: [ | |
'--disable-gpu', | |
'--headless' | |
] | |
}); | |
} | |
const chrome = await launchChrome(); | |
const protocol = await CDP({ | |
port: chrome.port | |
}); | |
// | |
const { DOM, Page, Emulation, Runtime } = protocol; | |
await Promise.all([ | |
Page.enable(), | |
Runtime.enable(), | |
DOM.enable() | |
]); | |
// const { frameId } = await Page.navigate({ url: 'about:blank' }); | |
const { frameId } = await Page.navigate({ url: 'http://www.redotheweb.com/DependencyWheel/' }); | |
console.log(`id: ${frameId}`); | |
await Page.loadEventFired(); | |
console.log('loaded'); | |
// const script1 = "document.querySelector('p').textContent"; | |
// const result = await Runtime.evaluate({ | |
// expression: script1 | |
// }); | |
// console.log(result.result.value); | |
// const ss = await Page.captureScreenshot({ | |
// format: 'png', | |
// fromSurface: true | |
// }); | |
// file.writeFile('screenshot.png', ss.data, 'base64', function(err) { | |
// if (err) { | |
// console.log(err); | |
// } | |
// }); | |
// const { frameId } = await Page.navigate({ url: 'about:blank' }); | |
const html = ` | |
<pre><code> | |
(function(global) { | |
var modules = {}; | |
global.require = function(name) { | |
return modules[name]; | |
}; | |
global.define = function(name, definition) { | |
if (!(name in modules)) { | |
modules[name] = typeof definition === 'function' ? definition.call(this) : definition; | |
} | |
}; | |
})(window); | |
</code></pre> | |
`; | |
// await Page.setDocumentContent({ frameId, html }); | |
let { data } = await Page.printToPDF({ | |
landscape: true, | |
printBackground: true, | |
marginTop: 0, | |
marginBottom: 0, | |
marginLeft: 0, | |
marginRight: 0 | |
}); | |
file.writeFile('print.pdf', Buffer.from(data, 'base64'), 'base64', function(err) { | |
if (err) { | |
console.log(err); | |
} | |
protocol.close(); | |
chrome.kill(); | |
}); | |
// protocol.close(); | |
// chrome.kill(); | |
// ======== | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* chrome-remote-interface: JavaScript API, обеспечивающее простую абстракцию для команд и уведомлений | |
* | |
* chrome-launcher: позволяет нам запускать Chrome из Node.js кроссплаторменно | |
*/ | |
const chromeLauncher = require('chrome-launcher'); | |
const CDP = require('chrome-remote-interface'); | |
const file = require('fs'); | |
let chrome; | |
let protocol; | |
// let DOM, Page, Emulation, Runtime; | |
let frameId; | |
let pdfData; | |
const html = ` | |
<pre><code> | |
(function(global) { | |
var modules = {}; | |
global.require = function(name) { | |
return modules[name]; | |
}; | |
global.define = function(name, definition) { | |
if (!(name in modules)) { | |
modules[name] = typeof definition === 'function' ? definition.call(this) : definition; | |
} | |
}; | |
})(window); | |
</code></pre> | |
`; | |
function launchChrome() { | |
return chromeLauncher.launch({ | |
chromeFlags: ['--disable-gpu', '--headless'] | |
}); | |
} | |
function end() { | |
protocol.close(); | |
chrome.kill(); | |
} | |
launchChrome() | |
.then(chr => { | |
chrome = chr; | |
return chrome; | |
}) | |
.then((chrome) => { | |
return CDP({ | |
port: chrome.port | |
}) | |
}) | |
.then(prtcl => { | |
protocol = prtcl; | |
DOM = protocol.DOM; | |
Page = protocol.Page; | |
Emulation = protocol.Emulation; | |
Runtime = protocol.Runtime; | |
return protocol; | |
}) | |
.then(() => { | |
return Promise.all([ | |
Page.enable(), | |
Runtime.enable(), | |
DOM.enable() | |
]) | |
}) | |
.then(() => Page.navigate({ url: 'about:blank' })) | |
.then( ({ frameId }) => { | |
frameId = frameId; | |
return frameId; | |
}) | |
.then((frameId) => Page.setDocumentContent({ frameId, html })) | |
.then(() => Page.printToPDF({ | |
landscape: true, | |
printBackground: true, | |
marginTop: 0, | |
marginBottom: 0, | |
marginLeft: 0, | |
marginRight: 0 | |
})) | |
.then(({ data }) => { | |
pdfData = data; | |
return pdfData; | |
}) | |
.then((pdfData) => { | |
return new Promise(function(resolve, reject) { | |
file.writeFile('print.pdf', Buffer.from(pdfData, 'base64'), 'base64', function(err) { | |
if (err) { | |
console.log(err); | |
return reject(err); | |
}; | |
return resolve(); | |
}); | |
}) | |
}) | |
.catch(console.error) | |
.then(end); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puppeteer = require('puppeteer'); | |
const html = ``; | |
(async() => { | |
const browser = await puppeteer.launch(); | |
const page = await browser.newPage(); | |
// await page.setContent(html); | |
await page.goto(`data:text/html,${html}`, { | |
waitNetworkIdle: true, | |
waitLoad: true, | |
waitUntil: 'networkidle2' | |
}); | |
await page.emulateMedia('screen'); | |
await page.pdf({ | |
path: 'print.pdf', | |
printBackground: true, | |
format: 'A4', | |
}); | |
await browser.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment