Search code examples
node.jsnpmpdf-generation

Add image in header using html-pdf node module


I am using this to convert the html to PDF.The conversions are really good.But the problem is to add header and footer in the PDF pages.In the options if i add the header text i got the result what i expected.

//Options

    var options = {
    "header": {
        "height": "45mm",
        "contents": "<div style='text-align: center;'>Author: Marc Bachmann</div>" // If i add image in content it wont work
    // sample i tried 
      },
      "footer": {
        "height": "28mm",
        "contents": "<span style='color: #444;'>{{page}}</span>/<span>{{pages}}</span>"
      }
    }
// Tried this in contents <img src="image path" />
    var result = <div class="container"> HTML CONTENT</div>';

        pdf.create(result, options).toFile(fileName + ".pdf", function(err, res) {
        if (err) {
        console.error(err);
        callback();
        }

Then if i add the image tag in the header(contents) option i didn't get the image in the generated PDF. Can you please give me a solution for this thanks.


Solution

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