简体   繁体   English

在Node.js中使用html-pdf时如何加载外部资产(图像,样式表等)

[英]How to load external assets (image, stylesheets, etc) when using html-pdf in Node.js

I'm using html-pdf ( NPM page ) to generate PDF files in my Node.js app. 我正在使用html-pdfNPM页面 )在Node.js应用程序中生成PDF文件。 The way I'm doing it, is first I render the HTML content using Handlebars and then feed the resulting buffer to html-pdf 's create() method. 我这样做的方式是,首先使用Handlebars渲染HTML内容,然后将结果缓冲区提供给html-pdfcreate()方法。 Like this: 像这样:

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);
    });
});

I'm using Express, and I serve my assets via routes for each type. 我正在使用Express,并且通过每种类型的路线来提供资产。 So I load them onto a regular HTML like this 所以我将它们加载到这样的常规HTML上

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

The problem is, these fail to load when the PDF is generated. 问题是,这些文件在生成PDF时无法加载。 I tried doing it like this: 我尝试这样做:

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

I've also tried adding base property to pdfProperties 我也尝试过将base属性添加到pdfProperties

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

But it still doesn't work. 但这仍然行不通。

Found it. 找到了。 I should set pdfProperties.base to http://localhost:8080 instead of http://localhost:8080/ (no trailing slash). 我应该将pdfProperties.base设置为http://localhost:8080而不是http://localhost:8080/ (不带斜杠)。

Or set it dynamically to req.protocol + '://' + req.get('host') . 或将其动态设置为req.protocol + '://' + req.get('host')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM