Amit Raj
Amit Raj

Reputation: 1378

Generate a report in PDF format in nodes

I am generating a tabular(Data grid) report which is in a text file in nodes. I want to generate the same report in PDF format so that the report will not be editable. I searched on the internet but only way I found from HTML but I don't want to use HTML.

Can it be possible? If yes then how?

Upvotes: 0

Views: 737

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

You can use PDFKit: http://pdfkit.org/ to do this I believe, here's a simple example, I've made lines a global now.

var content = [];
for(var i = 0; i < 30; i++) {
    content.push('Content line ' + i);
}

lines =[]; lines = Array.from(Array(content.length).keys()).map((n) => content[n]);  

var fs = require('fs');
var PDFDocument = require('pdfkit');

function printLinesToPDF() {

    return new Promise((resolve) => {

        var pdf = new PDFDocument({
          size: 'A4', 
          info: {
            Title: 'Example file',
            Author: 'Me',
          }
        });

        console.log('Printing %d line(s) to PDF', lines.length);
        lines.forEach((line) => pdf.text(line));

        var stream = fs.createWriteStream('./example.pdf');
        pdf.pipe(stream);

        pdf.flushPages();
        pdf.end();

        stream.on('finish', function() {
            resolve();
        });

    });
}

printLinesToPDF().then(() => {
    console.log('All done');
});

Upvotes: 1

Related Questions