In RMarkdown Word document, how to make table of c

2020-07-19 03:19发布

问题:

When an RMarkdown document is knit to Word, the Table of Contents (if there is one) always appears at the beginning of the document. If I want to, say, make the Table of Contents appear on the second page of the document, how do I do so?

If I was knitting to HTML I could use this method, but it doesn't seem to work for Word. Meaning, I create a Word template to be used in the reference_docx YAML argument and put the Table of Contents at the bottom of this template, but when I knit a report the Table of Contents appears at the front of the document.

Preferably, I'd like to use a solution that doesn't rely on VBA/VBS and instead uses RMarkdown and (if necessary) a reference_docx file only.

回答1:

As explained here, based on this and this, you could change the style of the date in the Word document to add a page break after it.

Of course, that only separates the title page from the table of contents and if you want to insert other pages between those two, it wouldn't work.

But at least that's an idea to start from.



回答2:

I've just been playing around with this issue myself. Unfortunately, I don't think Word allows you to modify a style to insert a break after a style, only before.

However, the TOC header is a style that is created when a TOC is included and can be modified. If you change the TOC header style to include a page break before, save this as your reference style document and run it forces the TOC onto a new page when knit.

As @Ben notes though this only allow you to move the TOC off the title page, not insert it where you want within the document.



回答3:

I was searching for a solution to this today and came across Garrick Aden‑Buie's blog post and render_toc() function.

Full details of which can be found here or his gist

This function allowed me to move the TOC later in to the document.