Add image in header using html-pdf node module

让人想犯罪 __ 提交于 2019-12-03 12:17:18

It is possible to add the image in options header. 1.Load the image in html body with "display:none" style. 2.Then add the image in the options header By doing this the image is cached and can attach the image in header.

    var options = {
    "format": 'Letter',
    "orientation": "portrait",
    "header": {
    "contents": "<img src='image path' />",
        "height": "30mm"
  },
  "footer": {
    "contents": footer
  }
}
pdf.create("<div style='display:none'><img src='image path' /></div>", options).toFile("sample.pdf", function(err, res) {
        if (err) {
                console.error(err);
                callback();
        } 
});

Refering to this issue on the github, you can't put your image directly in options.header, you have to put it in the body inside a <div id="pageHeader"></div>:

var pdf = require('html-pdf');
var path = require('path');

// this is very important, you have to put file:// before your path
// and normalize the resulting path
var imgSrc = 'file://' + __dirname + '/350x120.png';
imgSrc = path.normalize(imgSrc);
// or var imgSrc = path.join('file://', __dirname, '/350x120.png');

// Options
var options = {
    "header": {
      "height": "45mm",
      "contents": ""
    },
    "footer": {
      "height": "28mm",
      "contents": "<span style='color: #444;'>{{page}}</span>/<span>{{pages}}</span>"
    }
  }
// put your entire header here and the content of the page outside the <div id="pageHeader"></div>
var result = "<div id='pageHeader'><img src='" + imgSrc + "' /><div style='text-align: center;'>Author: Marc Bachmann</div></div>";
result += "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>";
var fileName = __dirname + '/test.pdf';
pdf.create(result, options).toFile(fileName, function(err, res) {
  if (err) {
    console.error(err);
  }
});

With this code, I get this pdf:

Created a simple NPM module for this purpose that can add arbitrary HTML and CSS to an existing PDF.

const pdf = require('add-html-to-pdf');

var options = {
  input: 'sample.pdf',
  output: 'done.pdf',
  html: "<div style='text-align: center;'>Author: Marc Bachmann</div>",
}

pdf.insertHTMLInPDF(options);

Maybe will be helpful for someone.

Shanoor answer is correct and code example he provided works well if you don't set "base" property for options.

So remove "base" property and make path full.

One more way to get the path to the image. This snippet

var projectRoot = process.cwd();
projectRoot = projectRoot.replace(/\\/g,'/');
var imgBase = 'file:///' + projectRoot + 'path to the image';

Will return something like this file:///C:/project folder/path to the image/img1.jpg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!