Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create pdf file using pdfkit in nodejs

I need to generate pdf file in 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 everytime I open the file, the file is corrupted. It says: 'Unable to open document File type plain text document (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's an error saying:

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

Then, what is the right way to generate pdf files in nodejs? Especially in part of:

doc.pipe fs.createWriteStream

Please help me. Thanks in advance!

like image 635
krisbie Avatar asked Mar 26 '14 14:03

krisbie


People also ask

How do I PDF as PDFKit?

Creating a PDF Document using PDFKit const PDFDocument = require('pdfkit'); const fs = require('fs'); let pdfDoc = new PDFDocument; pdfDoc. pipe(fs. createWriteStream('SampleDocument. pdf')); pdfDoc.

How do I use PDFKit?

There are two ways to use PDFKit in the browser. The first is to create an app using an module bundler like Browserify or Webpack. The second is to create a standalone pdfkit script as explained here.


4 Answers

Most of their documentation seems to be written in CoffeeScript. As cool as CoffeeScript is, that makes it a pain for those of us writing plain old JS.

So, anywhere you see spaces in their documentation, you should be able to wrap that function in parenthesis:

doc.pipe(fs.createWriteStream('output.pdf'));
like image 186
pastudan Avatar answered Sep 30 '22 04:09

pastudan


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.
});
like image 31
Nouman Dilshad Avatar answered Oct 01 '22 04:10

Nouman Dilshad


You have to call the fs module before that. Add this at the top of the file:

var fs = require('fs');
like image 35
Zlatko Avatar answered Sep 30 '22 04:09

Zlatko


It works for me:

doc.pipe(fs.createWriteStream('output.pdf'));
like image 44
Alex Avatar answered Oct 02 '22 04:10

Alex