Search code examples
rpdf-generationgridextragrob

adding a logo to a grid.table PDF output in R


I have a table output in pdf format and I want to customise it to bring in line with a corporate theme. However, I'm new to this area in R and still finding it difficult to find my feet in adding logos.

My original dataset is composed of over 600 rows of data and is sensitive, so I've used a sample dataset to demonstrate. So far, I've got the following code using the grid and gridExtra packages:

library(grid)
library(gridExtra)

Data <- data.frame(Staff = c("Rod","Barry","Cheiny"),
               M1 = c(50,40,55),
               M2 = c(60,50,55),
               M3 = c(55,50,45))


maxrow <- c(35);
npages <- ceiling(nrow(Data)/maxrow);
pdf("Data.pdf", height = 11, width = 10)
idx <- seq(1, maxrow)
grid.table(Data, rows = NULL, theme = ttheme_minimal())
grid.text("data",gp = gpar(fontsize = 12,fontface = "bold",alpha = 0.5), 
           vjust = -40,
           hjust = -0.5)
for (i in 2:npages){
  grid.newpage();
  if(i*maxrow <= nrow(Data)) {
    idx <- seq(1+((i-1)*maxrow), i*maxrow)
  }else{
    idx <- seq(1+((i-1)*maxrow), nrow(Data))
  }
  grid.table(Data, rows =NULL, theme = ttheme_minimal())
}
dev.off()

I'm getting a reasonable output at the moment, but I want to add a logo to each of the pages generated.

Anyone know how to add a logo that will repeat across all the pages?


Solution

  • It's easy to add elements with grid.draw(), but the design is up to you

    library(grid)
    library(gridExtra)
    
    Data <- data.frame(Staff = c("Rod","Barry","Cheiny"),
                       M1 = c(50,40,55),
                       M2 = c(60,50,55),
                       M3 = c(55,50,45))
    
    library(png)
    img <- readPNG(system.file("img", "Rlogo.png", package="png"))
    
    footer <- grobTree(rectGrob(y=0,vjust=0,gp=gpar(fill="grey97",col=NA), height=unit(1,"in")),
                       textGrob(y=unit(0.5,"in"), expression(Corporate^TM~line~(c))),
                       rasterGrob(img, x=1, hjust=1,y=unit(0.5,"in"),height=unit(1,"in")-unit(2,"mm")))
    
    maxrow <- c(35);
    npages <- ceiling(nrow(Data)/maxrow);
    pdf("Data.pdf", height = 11, width = 10)
    idx <- seq(1, maxrow)
    grid.table(Data, rows = NULL, theme = ttheme_minimal())
    grid.draw(footer)
    grid.text("data",gp = gpar(fontsize = 12,fontface = "bold",alpha = 0.5), 
              vjust = -40,
              hjust = -0.5)
    for (i in 2:npages){
      grid.newpage();
      if(i*maxrow <= nrow(Data)) {
        idx <- seq(1+((i-1)*maxrow), i*maxrow)
      }else{
        idx <- seq(1+((i-1)*maxrow), nrow(Data))
      }
      grid.table(Data, rows =NULL, theme = ttheme_minimal())
      grid.draw(footer)
    }
    dev.off()