Home > database >  How to find the width of a knitR pdf so I can center text
How to find the width of a knitR pdf so I can center text

Time:10-05

I am creating a PDF using KnitR, whoever I would like to figure out what the exact width of the document is, or how I can set it. Once I have the correct width I can center my text using this. Right now I am using getOption("width") but this seems unaccurate

centerText <- function() {
  width <- getOption("width")
  out <- "your text"
  ws <- rep(" ", floor((width - nchar(out))/2))
  cat(ws, out, sep = "")
}
centerText()  

I haven't been able to find better code to center text inside a code chunk, but if anyone knows a better way that would be much appreciated.

CodePudding user response:

Since you are creating pdfs, I think a easier solution would be using latex.

---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## R Markdown

### centering a text

```{r, results='asis'}
centerText <- function(text) {
  out <- paste0("\\centerline{", text, "}")
  cat(out)
}
centerText("Lorem ipsum dolor sit amet")
```

### centering a paragraph

```{r, results='asis'}
centerParagraph <- function(text) {
  out <- paste0("\\begin{quotation}\n\\noindent\n", text, "\\end{quotation}\n")
  cat(out)
}

centerParagraph("Lorem ipsum dolor sit amet consectetur adipiscing elit, urna
consequat felis vehicula class ultricies mollis dictumst, aenean non a in donec
nulla. Phasellus ante pellentesque erat cum risus consequat imperdiet aliquam,
integer placerat et turpis mi eros nec lobortis taciti, vehicula nisl litora tellus
ligula porttitor metus. ")
```

Centering text


  • Related