首页 > 解决方案 > 对齐表格中的文本和图像 - pdf 输出

问题描述

我正在使用 bookdown 制作一个 pdf 文档。在文档中,我有一个表格,在表格中的一些单元格中,我有 png 图像。

我可以成功地构建这本书,但是图形和文本的对齐方式不匹配。看起来所有文本都与单元格的底部对齐,而图像则与单元格的顶部对齐。

我尝试使用该pander软件包而不是kableExtra并得到完全相同的结果。

这是一个例子:

---
site: bookdown::bookdown_site
documentclass: book
output:
  bookdown::pdf_book:
    toc: false
    includes:
delete_merged_file: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message=FALSE, cache=TRUE)
library(kableExtra)
library(knitr)
```

# Hello World

I think the world is flat 

```{r}
flag = "http://flagpedia.net/data/flags/mini/gb.png"
download.file(flag,'flag.png', mode = 'wb')

tbl_img <- data.frame(
col1 = c("row1", "row2"),
col2 = c("",
           ""),
col3 = c(
  "here is a whole bunch of text to show how the images and text in the table are not properly aligned.", 
  "here is a whole bunch of text to show how the images and text in the table are not properly aligned."))
tbl_img %>%
kbl(booktabs = T) %>%
column_spec(2, image = spec_image(
c("flag.png", "flag.png"), 600, 400)) %>%
   column_spec(3, width = "5cm")
```

产生这个:

在此处输入图像描述

是否可以让第 1 列和第 3 列中的文本在其单元格中垂直对齐(文本从单元格的左上角开始)?

标签: rr-markdownbookdownkableextra

解决方案


我在过去kable 中使用了@Lyngbakr 描述的解决方法:垂直对齐不适用于 pdf 输出

---
site: bookdown::bookdown_site
documentclass: book
output:
  bookdown::pdf_book:
    toc: false
header-includes:
  - \usepackage[export]{adjustbox}
delete_merged_file: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message=FALSE, cache=TRUE)
library(kableExtra)
library(knitr)
```

# Hello World
I think the world is flat 

```{r}
flag = "http://flagpedia.net/data/flags/mini/gb.png"
download.file(flag,'flag.png', mode = 'wb')

tbl_img <- data.frame(
col1 = c("row1", "row2"),
col2 = c("\\includegraphics[valign=T,scale=2.5,raise=2mm]{flag.png}",
         "\\includegraphics[valign=T,scale=2.5,raise=2mm]{flag.png}"),
col3 = c(
  "here is a whole bunch of text to show how the images and text in the table are not properly aligned.", 
  "here is a whole bunch of text to show how the images and text in the table are not properly aligned."))
tbl_img %>%
  kbl(booktabs = T, escape = F) %>%
  kable_styling(full_width = T)
```

在此处输入图像描述


推荐阅读