1

I was hoping to expand on print to pdf file using grid.table in r - too many rows to fit on one page in order to add a title to the PDF

title <- "Table 1: Iris Data"
d <- iris[sample(nrow(iris), 187, TRUE),]
d$another <- "More Data"
d$column <- "Even More Will it Be off the Page"
The Provided Answer
library(gridExtra)
library(grid)
d <- iris[sample(nrow(iris), 187, TRUE),]
d$another <- "More Data"
d$column <- "Even More Will it Be off the Page"
tg <- tableGrob(d, rows = seq_len(nrow(d))) 

fullheight <- convertHeight(sum(tg$heights), "cm", valueOnly = TRUE)
margin <- unit(0.51,"in")
margin_cm <- convertHeight(margin, "cm", valueOnly = TRUE)
a4height <- 29.7 - margin_cm
nrows <- nrow(tg)
npages <- ceiling(fullheight / a4height)

heights <- convertHeight(tg$heights, "cm", valueOnly = TRUE) 
rows <- cut(cumsum(heights), include.lowest = FALSE,
            breaks = c(0, cumsum(rep(a4height, npages))))

groups <- split(seq_len(nrows), rows)

gl <- lapply(groups, function(id) tg[id,])

pdf("multipage.pdf", paper = "a4", width = 0, height = 0)
for(page in seq_len(npages)){
  grid.newpage()
  grid.rect(width=unit(21,"cm") - margin,
            height=unit(29.7,"cm")- margin)
  grid.draw(gl[[page]])
}
## alternative to explicit loop:
## print(marrangeGrob(grobs=gl, ncol=1, nrow=1, top=NULL))
dev.off()

How can I change this code so that I can add title to the first page of the PDF?

MayaGans
  • 1,815
  • 9
  • 30
  • 1
    A couple things: can you simplify this just to what's needed to recreate it? See the *minimal* part of [mcve]—we probably don't need to recreate the data manipulation, just the data you're actually working with in the end. It also looks like you've repeated code by accident. Also, any reason why you need to draw the table, not just use something like `knitr::kable` to print it as copyable, searchable text? – camille Jan 17 '20 at 16:30
  • I'm using this code within a shiny downloadHandler - can you use knitr::kable to export a dataframe as a PDF? – MayaGans Jan 17 '20 at 17:05
  • 1
    I'm not familiar with doing that in Shiny, but I would imagine so. [This](https://stackoverflow.com/q/46471756/5325862) post looks like it might help – camille Jan 17 '20 at 18:04

0 Answers0