How to generate QR codes with R and publish with R Markdown

Have you ever wondered about creating a QR code and adding it to your R Markdown report? According to Wikipedia, the QR code (abbreviated from Quick Response Code) is a type of matrix barcode designed in Japan for the automotive industry. Nowadays, QR codes are scanned with a smartphone; they contain numeric or alphabetic data and often link to a website or application.

In this post, I will show how to generate a QR code and add it to the header of an R Markdown report. It can be very handy to include an email address or a website link as a QR code in the PDF reports generated with R Markdown before you share them with collaborators.

Loading the library

We start by loading the qrcode package, which provides the function for generating QR codes.

library(qrcode)

In order to include the QR code in the header of the PDF report, I will first create a QR code and save it as a PNG file. Here, the QR code links to the website of DataScience+.

Create the QR code

png("qrplot.png")
qrcode_gen("https://datascienceplus.com/")
dev.off()

Add the QR code to the R Markdown report

The code below is an R Markdown document that includes the graphicx and fancyhdr packages in its header. The graphicx package serves to load the qrplot.png file we generated, and fancyhdr places it in the header. The command \renewcommand{\headrulewidth}{0pt} is used to remove the default line that the fancyhdr package adds in the header. I could place the qrplot.png in the footer as well; to do so, I would change \fancyhead to \fancyfoot.

---
title: "PDF Output File"
output: pdf_document
header-includes:
-   \usepackage{graphicx}
-   \usepackage{fancyhdr}
-   \pagestyle{fancy}
-   \fancyhead[R]{\includegraphics[height=1cm]{qrplot.png}}
-   \fancyhead[L]{}
-   \fancypagestyle{plain}{\pagestyle{fancy}}
-   \renewcommand{\headrulewidth}{0pt}
---

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see .

When you click the **Knit** button a document will be generated that includes both contents as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

Knitting the R Markdown document with knitr will create a PDF file with the QR code in the header of every page. A screenshot of the PDF output is presented below.

That’s it — with just a few lines of code, your reports can carry a scannable link. From now on, don’t forget to add a QR code to your reports.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.