【问题标题】:How to load external assets (image, stylesheets, etc) when using html-pdf in Node.js在 Node.js 中使用 html-pdf 时如何加载外部资产(图像、样式表等)
【发布时间】:2018-05-10 07:24:37
【问题描述】:

我正在使用html-pdf (NPM page) 在我的 Node.js 应用程序中生成 PDF 文件。我这样做的方式是,首先我使用 Handlebars 渲染 HTML 内容,然后将生成的缓冲区提供给 html-pdfcreate() 方法。像这样:

var pdfProperties = {
    format: "A4"
}

fs.readFile('views/project-evaluation-print.hbs', {encoding: 'utf8'}, function(err, data) {
    if (err) return next(err);
    var source = data;
    var html = render(source, pageParameters);
    htmlPdf.create(html, pdfProperties).toStream(function(err, stream) {
        if (err) return next(err);
        stream.pipe(res);
    });
});

我正在使用 Express,我通过路由为每种类型提供我的资产。所以我将它们加载到这样的常规 HTML 中

<link rel="stylesheet" href="/stylesheets/home-page.css">
<img src="/images/logos/app-logo.png">

问题是,这些文件在生成 PDF 时无法加载。我试过这样做:

<link rel="stylesheet" href="localhost:8080/stylesheets/home-page.css">
<img src="localhost:8080/images/logos/app-logo.png">

我也尝试将base 属性添加到pdfProperties

var pdfProperties = {
    format: "A4",
    base: "http://localhost:8080/"
}

但还是不行。

【问题讨论】:

    标签: node.js pdf phantomjs


    【解决方案1】:

    找到了。我应该将pdfProperties.base 设置为http://localhost:8080 而不是http://localhost:8080/(没有尾部斜杠)。

    或者动态设置为req.protocol + '://' + req.get('host')

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2021-07-31
      • 2020-06-05
      • 1970-01-01
      • 2011-09-23
      相关资源
      最近更新 更多