如何使用不同的“dev.off()”与knitr(自动裁剪数字)

问题描述 投票:0回答:1

我想在pdf()文档中使用我自己的.Rnw绘图设备,使用knitr转换为PDF。在生成数字的PDF之后,它应该调用pdfCrop.off()而不是dev.off()(或任何knitr调用);这将完美地裁剪出最终的数字。如何才能做到这一点?

以下MWE工作(但没有裁剪)if(*)被注释掉(以及正确关闭之前的行)。

\documentclass{article}

\begin{document}
<<knitr_options, echo = FALSE, results = "hide", purl = FALSE>>=
## Custom graphics device (for cropping .pdf):
pdfCrop <- function(file, width, height, ...)
{
    f <- file
    grDevices::pdf(f, width = width, height = height, onefile = FALSE)
    assign(".pdfCrop.file", f, envir = globalenv())
}
pdfCrop.off <- function() # used automagically
{
    grDevices::dev.off() # closing the pdf device
    f <- get(".pdfCrop.file", envir = globalenv())
    system(paste("pdfcrop --pdftexcmd pdftex", f, f, "1>/dev/null 2>&1"),
           intern = FALSE) # crop the file (relies on PATH)
}

## knitr options
knitr::opts_chunk$set(fig.path = "./fig_", background = "#FFFFFF",
                      dev = "pdfCrop", fig.ext = "pdf") # (*) => how to use pdfCrop.off() instead of dev.off()?
@

<<MWE>>=
<<fig-MWE, eval = FALSE, echo = FALSE>>=
plot(1:10, 10:1)
@
\setkeys{Gin}{width=\textwidth}
\begin{figure}[htbp]
  \centering
  \framebox{
<<figMWE, echo = FALSE, fig.width=6, fig.height=6>>=
<<fig-MWE>>
@
}
\caption{Just some text to show the actual textwidth in order to see that the
  figure is not perfectly horizontally aligned due to some white space which can
  be avoided by properly crop the figure with an adequate pdf crop device.}
\end{figure}

\end{document}
knitr rnw
1个回答
0
投票

knitr已经提供了基于pdfcrop的裁剪设备,所以我们可以通过钩子使用它:

\documentclass{article}

\begin{document}
<<knitr_options, echo = FALSE, results = "hide", purl = FALSE>>=
## knitr options
library(knitr)
knit_hooks$set(crop = hook_pdfcrop)
knitr::opts_chunk$set(fig.path = "./fig_", # all figures are saved as fig_*
                      background = "#FFFFFF", # avoid color
                      crop = TRUE) # always crop
@

<<MWE>>=
<<fig-MWE, eval = FALSE, echo = FALSE>>=
plot(1:10, 10:1)
@
\setkeys{Gin}{width=\textwidth}
\begin{figure}[htbp]
  \centering
<<figMWE, echo = FALSE, fig.width=6, fig.height=6>>=
<<fig-MWE>>
@
\caption{Just some text to show the actual textwidth in order to see that the
  figure is not perfectly horizontally aligned due to some white space which can
  be avoided by properly crop the figure with an adequate pdf crop device.}
\end{figure}

\end{document}
© www.soinside.com 2019 - 2024. All rights reserved.