Search code examples
htmlcssrmarkdownwkhtmltopdf

Implementing CSS style for page breaks "breaks" the tables of contents in R Markdown


Owing to issues with getting my document to look pleasing in knitr's export to pdf, I'm converting the html file for my Markdown project to pdf through the wkhtmltopdf cmd line utility tool.

A very basic Markdown doc replicates my issue:

---
title: "Untitled"
output: 
  html_document:
    df_print: paged
    toc: true
    number_sections: true
---

## ALPHA Header

### Alpha sub-1

### Alpha sub-2

## BETA Header

### Beta sub-1

### Beta sub-2

This generates a html file with the table of contents - but no page breaks when I go to convert this file through wkhtmltopdf.

I sourced answers from this Github query, trying to implement the custom CSS style type recommended. Note, I don't really know much html/CSS.

I modified the markdown code after the YAML (which remains unchanged) by:

<style type="text/css" media="screen,print">
       /* Page Breaks */

/***Always insert a page break before the element***/
       .pb_before {
           page-break-before: always !important;
       }
</style>

<div class="page1 pb_before">
## ALPHA Header
</div>
<div class="page2 pb_before">
### Alpha sub-1
</div>
<div class="page3 pb_before">
### Alpha sub-2
</div>
<div class="page4 pb_before">
## BETA Header
</div>
<div class="page5 pb_before">
### Beta sub-1
</div>
<div class="page6 pb_before">
### Beta sub-2
</div>

Knitting this version, the numbering system for the headers and the table of contents have disappeared, however now when I go to convert the html file to pdf by wkhtmltopdf, I now get a seperate page for each header.

So my question is - how do I synthesise the two together, whereby I have a table of contents and numbered headers after exporting to html, as well as having html/CSS code prepped to allow me to have page breaks after each header when I've converted through wkhtmltopdf.


Solution

  • I found a hacky solution for this:

    Insert:

    <div class="page1 pb_after">
    &nbsp;
    </div>
    

    Before every header I want a seperate page for.