Search code examples
javascripthtmlpdf-generationpdfmake

Generating pdfmake header & footer from HTML: incomplete rendering


I'm working on a browser app that should export a PDF. This PDF must have user-defined headers and footers. These headers and footers are stored in a database as strings and are fetched with an API call.

I am using pdfmake and htmltopdfmake for this. I am parsing these HTML strings like this:

exportReportToPDF (tableData, tableKeyMap, reportSettings, reportTitle) {
      /* Style constants */
      const blue = '#044e99'
      const marginArray = [40, 5, 0, 10]
      const documentDefinition = {}
      const rawHTMLStyles = {
        h1: {
          fontSize: 16,
          color: blue,
          margin: marginArray
        },
        h2: {
          fontSize: 14,
          color: blue,
          margin: marginArray
        },
        h3: {
          fontSize: 12,
          color: blue,
          margin: marginArray
        },
        p: {
          fontSize: 8,
          margin: marginArray
        },
        hr: {
          margin: [0, 0, 0, 0]
        }

      }

      /* Generate header and footer */
      if (reportSettings.header && reportSettings.footer) {
        const header = htmlToPdfmake(reportSettings.header, {
          defaultStyles: rawHTMLStyles,
          imagesByReference: true
        })
        const footer = htmlToPdfmake(reportSettings.footer, {
          defaultStyles: rawHTMLStyles,
          imagesByReference: true
        })
        documentDefinition.header = header.content
        documentDefinition.footer = footer.content
      }

      /* irrelevant code redacted  */

      pdfMake.createPdf(documentDefinition).open()
    },

This isn't working well. If i pass this as reportSettings to the function, the header displays incorrectly. The <h1> appears, but the <h2> doesn't.

{
  "id": 1,
  "title": "Prueba",
  "header": "<h1>Lorem Ipsum Dolor Sit Amet</h1><h2>consectetur adipiscing elit</h2>",
  "footer": "<p>Lorem ipsum 2021</p>",
  "created": "2021-07-06T15:21:10.864259Z",
  "updated": "2021-07-06T15:21:10.864358Z",
  "creator": 1
}

What am I doing wrong? How should I make this HTML render? Thanks in advance!


Solution

  • Found a solution in this GitHub issue! Increasing the document's pageMargins makes the hidden lines appear. It seems like the body of the document hides the header and footer as if it had a higher z-index.

    Like this:

    exportReportToPDF (tableData, tableKeyMap, reportSettings, reportTitle) {
          const documentDefinition = {
            pageMargins: [40, 80, 40, 80]
          }
    
         /* ... */
    
          pdfMake.createPdf(documentDefinition).open()
        },