在Node.js中使用pdfkit创建PDF文件

5

我需要使用pdfkit在node.js中生成pdf文件:

这是我的代码:

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

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

doc.end();

它将会创建一个pdf文件: 'output.pdf',但是每次我打开这个文件,都会出现文件损坏的错误提示。错误提示是:"无法打开文档, 不支持纯文本文档(text/plain)文件类型"。

之后,我尝试了以下方法:

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

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

doc.end();

但是出现了一个错误提示:
doc.pipe fs.createWriteStream('output.pdf');
         ^^
Syntax error: Unexpected Identifier

然后,在Node.js中生成PDF文件的正确方法是什么?特别是在以下方面:
doc.pipe fs.createWriteStream

Please help me. Thanks in advance!

4个回答

9
大部分的文档似乎都是用CoffeeScript编写的。虽然CoffeeScript很酷,但对于我们这些编写普通JS的人来说,这是一种痛苦。
因此,无论在文档中看到什么地方有空格,您都应该能够将该函数包裹在括号中:
doc.pipe(fs.createWriteStream('output.pdf'));

2

尝试使用这段代码。

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

对我来说它有效:

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

但是很多时候会生成空的PDF文件,你有遇到过吗?请求查看我的问题 - https://stackoverflow.com/q/54930985/2034750 - 151291

1

在此之前,您需要调用fs模块。 将以下代码添加到文件顶部:

var fs = require('fs');

1
已经被调用了。已经找到答案了。Node.js的正确语法是:doc.pipe(fs.createWriteStream('out.pdf')); - krisbie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接