luca
luca

Reputation: 3318

Print variable inside the footer of PDF creation

I need to print a object field inside the footer of a page. At the moment I have:

async function createPdf(obj, res) {
        //other code
        const pdf = await page.pdf({ 
        format: 'A4', 
            printBackground: true, 
            displayHeaderFooter : true,
            headerTemplate : "",
        footerTemplate : "<style>.footer{width: 100%; font-size:12px; text-align:right; color:white; background:#161719; -webkit-print-color-adjust:exact; margin-bottom:-15px;}</style><div class='footer'><span>page </span><span class='pageNumber'></span>/<span class='totalPages'></span></div>",
            //margin top 0 removes header
            margin: {top: "00", bottom: "18"}
        });
        //other code
}

I need to print some obj filter inside of the footer, but all the ways I have tried, it prints obj as a string and not the content. Is it possible to accomplish my goal?

Upvotes: 0

Views: 837

Answers (1)

Grant Miller
Grant Miller

Reputation: 28999

In order to print a variable inside of the footer when creating a PDF with page.pdf(), you can use place the footerTemplate HTML inside of a template literal (``) and insert the variable inside of a placeholder (${}).

See the example below:

const example = 'Hello, world!';

const pdf = await page.pdf({
  format: 'A4',
  printBackground: true,
  displayHeaderFooter: true,
  headerTemplate: '',
  footerTemplate: `<style>
                   .footer {
                     background: #161719;
                     color: #fff;
                     -webkit-print-color-adjust: exact;
                     color-adjust: exact;
                     font-size: 12px;
                     margin-bottom: -15px;
                     text-align: right;
                     width: 100%;
                   }
                   </style>
                   <div class="footer">
                     <span>${example}</span> <!-- Variable Inside Footer -->
                     <span>page</span>
                     <span class="pageNumber"></span>/<span class="totalPages"></span>
                   </div>`,
  //margin top 0 removes header
  margin: {
    top: 0,
    bottom: 18,
  },
});

Upvotes: 1

Related Questions