user3142695 user3142695 - 7 months ago 71
Javascript Question

Meteor: Get server side generated file by clicking on a button

I'm using

pdfKit
to generate some pdf-files. The user should click on a button to get this file - which is generated at the server at that moment. Further more I'm using
Picker
for server side routing.

server.js

Picker.route('/generate/getPdf', function(params, req, res, next) {
var doc = new PDFDocument({size: 'A4', margin: 50});
doc.fontSize(12);
doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=test.pdf'
});
res.end(doc.outputSync());
});


html

<template name="example">
<button id="generatePdf">Generate it</button>
</template>


client.js

Template.example.events({
'click #generatePdf': function(event) {
HTTP.call( 'GET', 'http://localhost:3000/generate/getPdf', {}, function( error, response ) {
if (error) {
console.warn(error);
}
});
}
});


I would expect to get the pdf-file as I click on the button, but nothing is happening. If I go manually to the url, I'll get the file. So what am I doing wrong?

Answer

Because you are already setting the Content-Disposition header to be an attachment, the easiest solution is to start the download in a new tab.

Try removing your click #generatePdf event handler and do something like this in your template:

<a id="generatePdf" href="//localhost:3000/generate/getPdf" target="_blank">Click Me</a>