Create pdf file using pdfkit in nodejs

I need to create a pdf file using pdfkit in node.js:

I have this code:

doc = new PDFDocument;
doc.pipe; fs.createWriteStream('output.pdf');

doc.fontSize(15);
doc.text('Generate PDF!');

doc.end();

And it will create a pdf file: 'output.pdf', but every time I open the file, the file is corrupted. It says: "The document cannot be opened. A text document of type text (text / plain) is not supported . "

And then I tried:

doc = new PDFDocument;
doc.pipe fs.createWriteStream('output.pdf');

doc.fontSize(15);
doc.text('Generate PDF!');

doc.end();

But there is an error:

doc.pipe fs.createWriteStream('output.pdf');
         ^^
Syntax error: Unexpected Identifier

Then, what is the correct way to create PDF files in nodejs? Especially regarding:

doc.pipe fs.createWriteStream

Please help me. Thanks in advance!

+5
source share
4 answers

, , CoffeeScript. , CoffeeScript, , JS.

, , , :

doc.pipe(fs.createWriteStream('output.pdf'));
+9

fs . :

var fs = require('fs');
+1

This works for me:

doc.pipe(fs.createWriteStream('output.pdf'));
+1
source

Try this piece of code.

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

let options = {
 margins: 50
// you pdf settings here.
}
const doc = new PDFDocument(options);
let out = fs.createWriteStream('output.pdf')
doc.pipe(out);
doc.text('Hellow World.')
doc.end();
out.on('finish', function() {
    // what you want to do with the file.
});
+1
source

Source: https://habr.com/ru/post/1533555/


All Articles