Insert a logo in upper right corner of R markdown html document

Bruno Silva picture Bruno Silva · Mar 24, 2017 · Viewed 20.2k times · Source

I'm trying to put my company logo on the right corner of my html document

Here my code:

<script>
  $(document).ready(function() {
    $head = $('#header');
    $head.prepend('<div class="knitr source"><img src="logo.png" width="220px" align="right"   ></div>')
  });
</script>

---
title: "Title"
author: "Author"
date: "Date"
theme: bootstrap
output: html_document
keep_md: true
---

```{r echo=FALSE,  include=FALSE}
knitr::include_graphics('./logo.png')
```

<br>

## 1) Header

<br>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.

However, because the logo.png is a local file when sharing the html document people are not able to see it.

Additionally, I tried the following approach

---
title: "Title"
author: "Author"
date: "Date"

output: 
  html_document:
    css: markdown.css
    includes:
      in_header: extLogo.html
---

where extLogo.html

<div class="logos"><img src="logo.png" width="220px" align="right"></div>

But it creates a div outside the div where the Title is (<div class="container-fluid main-container">). Can anyone help on this?

Answer

alistaire picture alistaire · Mar 25, 2017

You can use htmltools::img with a little inline CSS for positioning. src can take a path directly, but when images aren't just handled like plots, sometimes knitting fails to convert images to a URI properly, which in turn causes them to fail to render. Using self_contained: false in the YAML is a quick solution, but it's not much harder to use knitr::image_uri to manually convert the image:

---
title: "Title"
author: "Author"
output: html_document
---


```{r, echo=FALSE}
htmltools::img(src = knitr::image_uri(file.path(R.home("doc"), "html", "logo.jpg")), 
               alt = 'logo', 
               style = 'position:absolute; top:0; right:0; padding:10px;')
```

---

# 1. Header

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.

page with logo