Skip to content

Instantly share code, notes, and snippets.

@rtnpro
Created April 22, 2020 17:33
Show Gist options
  • Select an option

  • Save rtnpro/a8d0aa7d194b9ed128d51cefe18a1c2c to your computer and use it in GitHub Desktop.

Select an option

Save rtnpro/a8d0aa7d194b9ed128d51cefe18a1c2c to your computer and use it in GitHub Desktop.
PDF/File creation and download using server-side ASYNC methods in Meteor
if (Meteor.isServer) {
/* Use Fibers/Future */
var Future = Npm.require('fibers/future');
/* Async Method */
function generatePDF(id, options, callback){
check(id, String);
check(options, Object);
check(callback, Function);
var err,
result,
docJson = Documents.findOne({ _id: id });
document = new DocumentClass({
doc: docJson
});
result = document.generateFile();
callback(err, result);
}
/* Meteor Method */
Meteor.methods({
generateFileDownload: function (id, options) {
var fut = new Future();
var boundCallback = Meteor.bindEnvironment(function (err, res) {
if(err) {
fut.throw(err);
} else {
fut.return(res)
}
});
generatePDF(id, options, boundCallback);
return fut.wait();
}
});
/* Download Action */
Router.route('/document/:id/download', function () {
var docId = this.params.id;
check(id, String);
generateFileAndReturnSettingsJSON = function () {
Meteor.call('generateFileDownload', { id: docId, options: {} }, function (err, res) {
if(err){
Meteor.Error(err);
} else {
return res;
}
});
}
var file = generateFileAndReturnSettingsJSON(),
stat = null;
try {
stat = fs.statSync(file.path);
} catch (_error) {
response.statusCode = 404;
response.end();
}
this.response.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=' + file.name,
'Content-Length': stat.size
});
fs.createReadStream(file.path).pipe(this.response);
}, {
where: 'server'
});
}
<template name="pageWithDownloadLink">
<a href="/document/{{_id}}/download">Download File</a>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment