首先,请注意,当this knitr feature request 将被实施时,您必须停止使用以下答案。
这个问题可以使用pandoclink attributes来解决。正如pandoc 文档中解释的那样,没有链接属性“后备是查看图像文件中嵌入的图像分辨率和 dpi 元数据”(我认为问题来自这种后备方法) .
链接属性是最近的pandoc 功能,在pandoc 1.16 中引入。 knitr 尚不支持,但根据上述功能要求将很快支持。
只要knitr不支持pandoc链接属性,这里有一个hacky提案来解决这个问题。它使用knitrplot hook。
---
output: word_document
---
```{r setup, echo=FALSE}
default_plot_hook <- knitr::knit_hooks$get('plot')
knitr::knit_hooks$set(plot = function(x, options) {
default_md <- default_plot_hook(x, options)
link_attr <- sprintf("{width=%sin height=%sin}", options$fig.width, options$fig.height)
sub("(!\\[.*]\\(.*\\))", paste0("\\1", link_attr), default_md)
})
```
```{r, echo=F}
plot(1:100)
```
说明
RMarkdown 文件 (.Rmd) 的渲染过程的第一步是生成一个普通的 markdown 文件 (.md)。 这是knitr的工作。
该过程的第二步是从此markdown 文件生成word 文件(.docx)。 这是pandoc的工作。
请注意,您可以使用YAML 标头中的keep_md 选项检查此中间markdown 文件:
---
output:
word_document:
keep_md: true
---
在knitr 的可用版本中,指向图像的链接由knitr 呈现,如下所示:
<!-- -->
没有链接属性,因此pandoc 使用其后备方法确定图像的尺寸。
建议的knitr plot hook 为链接添加宽度和高度属性。
它返回以下markdown:
{width=5in height=4in}<!-- -->
因此,pandoc 根据这些属性而不是后备方法确定图像的尺寸。
显然,要使用此提议,您的 pandoc 版本必须 >= 1.16。