Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr/Rmd: page break after n lines/n distance

Let me caveat by saying that this may be better suited as an html/css question but (a) I'm not too familiar with those techniques and (b) I wanted to keep it all in the family (R family) if possible.

I would like to use knitr to write academic style reports (APA 6 type guidelines) using Rmarkdown. I've got most aspects worked out but not page breaking. I can manually set page breaks with something like:

# report  ```{r setup, include=FALSE} # set global chunk options opts_chunk$set(cache=TRUE) ``` ------ ## Page 1  ```{r plot1} plot(1:10, 1:10) ``` ------ ## Page 2 

In the following .Rmd I'd like to programatically set those breaks after n lines/n distance. So let's say after 8 inches or 140 lines.

# report  ```{r setup, include=FALSE} # set global chunk options opts_chunk$set(cache=TRUE) ``` Initial Text. Yay!  ```{r plot1} plot(1:10, 1:10) ```  More Text.  Outstanding.  What Hadley's not calling it plyr2?  ```{r plot2, fig.width=4, fig.height=4} plot(1:10, 1:10) ```  `r paste(rep("So much text so little time!", 10000))` 

How can I programatically set page breaks after n distance. This is similar to how LaTeX would break a file into pages so if a figure takes too much space it would be forced to the next page.

EDIT Found this from a friend: http://www.w3.org/TR/css3-page/ may be helpful.

like image 864
Tyler Rinker Avatar asked Apr 23 '13 15:04

Tyler Rinker


1 Answers

Programatically. Create an HTML div. Set this div's width and height to a fixed amount and the overflow to scroll.

<div style="height:1000px; width: 500px; overflow-y: scroll;">     ... </div> 

Process your markdown into HTML elements. I have 5 h1 tags that are 300px tall each.

<h1 style="height:300px;">First</h1> <h1 style="height:300px;">Second</h1> <h1 style="height:300px;">Third</h1> <h1 style="height:300px;">Fourth</h1> <h1 style="height:300px;">Fifth</h1> 

These 5 h1 wont all fit on the same page. The page is only 1,000 pixels tall. Only 3 h1 tags will fit on this page. We'll need to insert a pagebreak after the third element.

Incrementally add each new item into the DOM. After inserting each item check to see if the browser's scroll bar is present. If it is, then we know that the item we just inserted was too big for this page; remove the item and insert a page break.

Before:

### First ### Second ### Third ### Fourth ### Fifth 

After:

### First ### Second ### Third ------ ### Fourth ### Fifth 

This would work for any element and you wouldn't have to worry about an item's height. Because, if the item you just inserted made the HTML div scroll then we need a page break. Images, videos, h1, h2, p, custom/dynamic css, anything.

UPDATE

You could also calculate the height of each div element. http://api.jquery.com/height/ That way recalculating a 54 page document would be much easier.

like image 150
Travis Avatar answered Sep 23 '22 05:09

Travis