Created
March 26, 2021 13:18
-
-
Save mbenedettini/e88b5d09a980944783f0705d248ae43a to your computer and use it in GitHub Desktop.
html2pdf in node using phantomjs
This file contains hidden or 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
// 2017 version based on phantomjs, probably much easier nowadays with puppeteer | |
'use strict'; | |
const Promise = require('bluebird'); | |
const fs = require('fs'); | |
const readFile = Promise.promisify(fs.readFile); | |
const unlink = Promise.promisify(fs.unlink); | |
const phantom = require('phantom'); | |
const logger = require('logger'); | |
function getRandomInt(min, max) { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
//The maximum is exclusive and the minimum is inclusive | |
return Math.floor(Math.random() * (max - min)) + min; | |
} | |
function html2pdf(content) { | |
let instance, page; | |
let filename = `/tmp/${getRandomInt(1, 100)}.pdf`; | |
return phantom.create().then(i => { | |
instance = i; | |
return instance.createPage(); | |
}).then(p => { | |
page = p; | |
page.property('viewportSize', { width: 1024, height: 600 }); | |
page.property('paperSize', { | |
format: 'A4', | |
orientation: 'portrait' | |
}); | |
return page.setContent(content, 'file://' + filename); | |
}).then(() => { | |
return page.render(filename, { | |
format: 'pdf' | |
}); | |
}).then(() => { | |
return instance.exit(); | |
}).then(() => { | |
return readFile(filename).then(data => { | |
return unlink(filename).return(data); | |
}); | |
}).catch(err => { | |
logger.error(err); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment