1

我对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];
    };

有人有想法吗?

4

1 回答 1

2

在您的情况下,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无法读取给定路径上的文件

根据对话,您必须将字体放在根文件夹中,但是问题是当我们创建字体对象时,我们提供了根路径,而该路径不适用于fs.readFileSync该行,因此您必须准确的字体路径

process.cwd().split('.meteor')[0]在字体路径前添加

我已经为相同的功能创建了示例,请点击下面的链接

https://github.com/daupawar/MeteorAsyncPdfmake

于 2016-06-15T05:27:00.630 回答