Saturday, 22 April 2017

Error: write after end pdfkit

I'm a novice with NodeJS and in my application I create pdf with pdfkit.

Sometimes when I call my method I got the error :

Error: write after end
at writeAfterEnd
at PDFReference.Writable.write
at PDFPage.write

It don't happens everytimes, it's a bit random. I understand that I try to close the doc before writing on it (asynchronous way), but I don't understand how to handle it.

My routes :

app.post('/api/contests/:_id/ranking', contestController.print_ranking);

function print_ranking(req, res) {
    var path = null;
    Contest.findById(req.params._id, function (err, contest) {
        path = Print.print_ranking(contest, req.body);
        format_response(res, 200, {'path': path});
    });
}

My printing function :

const PDFDocument = require('pdfkit'),
    doc = new PDFDocument(),
    fs = require('fs');
function print_ranking(contest, ranking) {
    var start_line_x = 40, x_end = 545, start_y = 40;

    doc.pipe(fs.createWriteStream('public/printed/' + contest._id + '_ranking.pdf'));

    doc.text('Category : ' + '', start_line_x, start_y);
    // [ ... ]

    doc.end();

    return 'printed/' + contest._id + '_ranking.pdf';
}

As I said, sometimes, everything goes well, sometimes not...

If you have any clues.

Thanks.



via Normand Julian

No comments:

Post a Comment