Search code examples
r-markdownmarkdownrstudioquarto

How to PDF render Quarto books with dynamic content?


I am writing my thesis using a Quarto book in HTML, which has some dynamic content (leaflet maps, plotly dynamic graphs). However, eventually, I will need to export the book in PDF/LaTeX, or at least Word (and then I can copy and paste into LaTeX).

When I try to export to PDF I of course run into this error:

Functions that produce HTML output found in document targeting pdf output. Please change the output type of this document to HTML. Alternatively, you can allow HTML output in non-HTML formats by adding this option to the YAML front-matter of your rmarkdown file:

always_allow_html: true

Note however that the HTML output will not be visible in non-HTML formats.

I did try to add the always_allow_html: true in my YAML file, but I get the same exact error. I also tried the conditional rendering with {.content-hidden unless-format="pdf"}, but I can't seem to get it working.

Has anyone experienced the same issue?


Solution

  • Using .content-visible when-format="html" and .content-visible when-format="pdf" works very smoothly.


    ---
    title: "Conditional Rendering"
    format: 
      html: default
      pdf: default
    ---
    
    ## Conditional Content in Quarto
    
    ::: {.content-visible when-format="html"}
    
    ```{r}
    #| message: false
    
    library(plotly)
    library(ggplot2)
    
    p <- ggplot(mtcars, aes(wt, mpg))
    p <-  p + geom_point(aes(colour = factor(cyl)))
    
    ggplotly(p)
    ```
    
    
    ```{r}
    #| message: false
    #| fig-pos: "H"
    #| fig-width: 4
    #| fig-height: 3
    
    library(leaflet)
    
    # took this example from leaflet docs
    m <- leaflet() %>%
      addTiles() %>%  # Add default OpenStreetMap map tiles
      addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
    m  # Print the map
    
    ```
    
    :::
    
    
    ::: {.content-visible when-format="pdf"}
    
    ```{r}
    
    library(plotly)
    library(ggplot2)
    
    p <- ggplot(mtcars, aes(wt, mpg))
    p <-  p + geom_point(aes(colour = factor(cyl)))
    
    p
    ```
    
    :::