我的 pdfmake 有问题。我想在 node.js 服务器上生成 PDF。我想从数据库加载数据并绘制一个漂亮的表格,然后将其保存到文件夹中。
var pdfMakePrinter = require('pdfmake/src/printer');
...
var fonts = {
Roboto: {
normal: './fonts/Roboto-Regular.ttf',
bold: './fonts/Roboto-Medium.ttf',
italics: './fonts/Roboto-Italic.ttf',
bolditalics: './fonts/Roboto-Italic.ttf'
}
};
var PdfPrinter = require('pdfmake/src/printer');
var printer = new PdfPrinter(fonts);
var docDefinition = {
content: [
'First paragraph',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
]
};
var pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream('pdf/basics.pdf')).on('finish', function () {
res.send(true);
});
生成的 PDF 为空。如果我添加图像,它会插入得很好。但不包括字体。字体的路径(示例中给出)是正确的。
有谁知道为什么没有嵌入字体以及如何在 Node.js 中做到这一点? pdfmake 文档中没有有效的示例。
经过一些调试,我发现应用程序在这个函数中的 fontWrapper.js 中崩溃了:
FontWrapper.prototype.getFont = function(index){
if(!this.pdfFonts[index]){
var pseudoName = this.name + index;
if(this.postscriptName){
delete this.pdfkitDoc._fontFamilies[this.postscriptName];
}
this.pdfFonts[index] = this.pdfkitDoc.font(this.path, pseudoName)._font; <-- Crash
if(!this.postscriptName){
this.postscriptName = this.pdfFonts[index].name;
}
}
return this.pdfFonts[index];
};
有人有想法吗?
最佳答案
TTF 在您的情况下不是问题,您可以使用任何字体在 Node.js 服务器上生成 PDF。
pdfmake 内部
TTFFont.open = function(filename, name) {
var contents;
contents = fs.readFileSync(filename);
return new TTFFont(contents, name);
};
在contents = fs.readFileSync(filename);
这一行
fs
无法读取给定路径上的文件
根据This对话时您必须将字体放在根文件夹中,
但问题是,当我们创建字体对象时,我们给出了根路径,并且该路径不适用于 fs.readFileSync
这一行,因此您必须精确的字体路径
在字体路径前添加process.cwd().split('.meteor')[0]
我已经创建了相同功能的示例,请点击下面的链接
关于node.js - pdfmake 不包含 node.js 中的字体/文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37168873/