Centering image and text in R Markdown for a PDF report

后端 未结 9 1664
情深已故
情深已故 2020-12-28 12:10

I want to center an image and/or text using R Markdown and knit a PDF report out of it.

I have tried using:

->Text<-

->![](image1.jpg)<-         


        
相关标签:
9条回答
  • 2020-12-28 12:44

    You can set the center (or other) alignment for the whole document as a Knitr option, using:

    knitr::opts_chunk$set(echo = TRUE, fig.align="center")
    
    0 讨论(0)
  • 2020-12-28 12:44

    The simple solution given by Jonathan works with a modification to cheat Pandoc. Instead of direct Latex commands such as

    \begin{center}
    Text
    \end{center}
    

    you can define your own commands in the YAML header:

    header-includes:
    - \newcommand{\bcenter}{\begin{center}}
    - \newcommand{\ecenter}{\end{center}}
    

    And then you use:

    \bcenter
    Text and more
    \ecenter
    

    This works for me for centering a whole document with many code chunks and markdown commands in between.

    0 讨论(0)
  • 2020-12-28 12:48

    There is now a much better solution, a lot more elegant, based on fenced div, which have been implemented in pandoc, as explained here:

    ::: {.center data-latex=""}
    Some text here...
    :::
    

    All you need to do is to change your css file accordingly. The following chunk for instance does the job:

    ```{cat, engine.opts = list(file = "style.css")}
    .center {
      text-align: center;
    }
    ``` 
    

    (Obviously, you can also directly type the content of the chunk into your .css file...).
    The tex file includes the proper centering commands.
    The crucial advantage of this method is that it allows writing markdown code inside the block.
    In my previous answer, r ctrFmt("Centered **text** in html and pdf!") does not bold for the word "text", but it would if inside a fenced div.

    For images, etc... the lua filter is available here

    0 讨论(0)
提交回复
热议问题