【问题标题】:pdfmake does not include fonts / text in node.jspdfmake 在 node.js 中不包含字体/文本
【发布时间】:2016-05-11 16:54:08
【问题描述】:

我对 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 文件已损坏。当我使用简单的 Arial.ttf 时,它可以工作。
  • 您能否将您的问题标记为已解决?

标签: node.js pdf server pdfmake


【解决方案1】:

在您的情况下,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]

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

https://github.com/daupawar/MeteorAsyncPdfmake

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 2017-08-25
    • 1970-01-01
    • 2014-10-06
    • 2018-04-23
    • 2020-11-28
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多