pythonhtml2pdf

How do I specify a header/footer for html2pdf to use when rendering a pdf?


I'm using the html2pdf python library, and would like to define a header and a footer to apply to each page (including fun things, like a page count for the footer). What is the most expedient method I can use to specify headers/footers with html2pdf?


Solution

  • Easy Blueberry! You can use pages and frames to define headers and footers by placing them in your HTML doc's style tag.

    <html>
        <head>
        <style>
        /* Page margins are defined using CSS */
        @page {
          margin: 1cm;
          margin-top:2.5cm;
          margin-bottom: 2.5cm;
    
        /* Header frame starts within margin-top of @page */
          @frame header {
          -pdf-frame-content: headerContent; /* headerContent is the #id of the element */
          top: 1cm;
          margin-left: 1cm;
          margin-right:1cm;
          height:1cm;
          }
    
        /* Footer frame starts outside margin-bottom of @page */
          @frame footer {
            -pdf-frame-content: footerContent;
            bottom: 2cm;
            margin-left: 1cm;
            margin-right: 1cm;
            height: 1cm;
          }
        }
        </style>
        </head>
        <body>
               <div id="headerContent">I'm a header!</div>
               <p>I could be some content</p>
               <div id="footerContent">I'm a footer! <pdf:pagenumber></div>
        </body>
    </html>
    

    pdf:pagenumber is a tag used to display page count. There are many more tags included. Just refer to the official documentation!

    Source: HTML2PDF Github Documentation