matsuo_basho matsuo_basho - 5 months ago 16
CSS Question

How to use a custom font in an RShiny App

I would like to incorporate a custom font in my Rshiny App. I have a hunch the code would go in tags$style, but haven't the actual code to include this.

Example code:

ui <- fluidPage(
tags$style( ),
column(12,
dataTableOutput("testtab")
) # close column
) #close fluidpage

server <- function(input, output, session) {
output$testtab <-
DT::renderDataTable({
tab <- data.frame(a = 1:10, b = 11:20, c = 21:30)
dat.tab <- datatable(tab) %>% formatPercentage('a', 0) %>%
formatCurrency(1:ncol(tab), '$')
return(dat.tab)
}) # close renderDataTable
} # close server

shinyApp(ui=ui, server=server)


For example's sake, let's say I want to use any custom font out there on the web.

Answer

This should help.

First you need to download the font from http://www.fontspace.com/gunarta/surabanglus and install it by clicking on the file with the ttf extension and clicking install. Here I have added tags to control the default body font, and tags that use the "id tag" to control the fonts in specific controls and the background colors.

There are other ways to do this using seperate CSS files, etc. But this is quick and easy and not too dirty.

library(shiny)
library(dplyr)
library(DT)

ui <- fluidPage(
  tags$style(HTML('body {font-family:"Times New Roman",Georgia,Serif; background-color:orange}')),
  tags$style(HTML('#testtab {font-family:"surabanglus",Georgia,Serif; background-color:lightblue}')),
  tags$style(HTML('#hello2 {font-family:"Courier",Georgia,Serif; background-color:pink}')),
  column(12,
         dataTableOutput("testtab"),
         actionButton("hello1","Hello There (uses font inherited from body)"),
         actionButton("hello2","Hello There again (uses Courier)")

  ) # close column,
) #close fluidpage

server <- function(input, output, session) {
  output$testtab <- DT::renderDataTable({
    tab <- data.frame(a = 1:10, b = 11:20, c = 21:30)
    dat.tab <- datatable(tab) %>% formatPercentage('a', 0) %>% 
      formatCurrency(1:ncol(tab), '$')
    return(dat.tab)
  }) # close renderDataTable
} # close server

shinyApp(ui=ui, server=server)

Yielding this:

enter image description here