Skip to content

Instantly share code, notes, and snippets.

@michaltakac
Last active July 30, 2022 19:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michaltakac/911e0ffeba06dc10925e to your computer and use it in GitHub Desktop.
Save michaltakac/911e0ffeba06dc10925e to your computer and use it in GitHub Desktop.
Generating PDF from website screenshot using Iron Router and Webshot
/**
* Generating PDF from website screenshot.
*
* Using iron:router's server-side route and meteorhacks:npm to load Webshot NPM package.
* Don't forget to add "webshot": "0.16.0" to your packages.json file. Example:
* {
* "webshot": "0.16.0"
* }
* Tried it with bryanmorgan:webshot but it didn't work so sticking to loading NPM package directly.
* Thanks to @nate-strauser (https://github.com/nate-strauser).
*/
Router.route('generatePDF', {
path: '/invoices/:_id/generate-pdf', // example route with _id param
where: 'server',
action: function() {
// Get invoice ID parameter
var invoiceId = this.params._id;
// Setting name for our generated PDF
var fileName = "invoice_" + invoiceId + ".pdf";
// Load NPM packages
var webshot = Meteor.npmRequire('webshot');
var fs = Npm.require('fs');
var Future = Npm.require('fibers/future');
var fut = new Future();
// Set path to your route here - Meteor.absoluteUrl() is your root url ("http://localhost:3000/")
var url = Meteor.absoluteUrl('invoices/' + invoiceId); // Meteor.absoluteUrl('path/to/your/route');
// How you want your PDF to look, it also waits 3 seconds just to make sure photo has been taken
var options = {
"renderDelay": 3000,
"paperSize": {
"format": "Letter",
"orientation": "portrait",
"margin": "1cm"
}
};
// Magic happens here...
webshot(url, fileName, options, function(err) {
if (err) {
return console.log(err);
} else {
fs.readFile(fileName, function (error,data) {
if (error) {
return console.log(err);
}
fs.unlinkSync(fileName);
fut.return(data);
});
}
});
// Give our generated PDF to the client
this.response.writeHead(200, {'Content-Type': 'application/pdf',"Content-Disposition": "attachment; filename=" + fileName});
this.response.end(fut.wait());
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment