0

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

如果 (*) 被注释掉(以及正确关闭之前的行),则以下 MWE 有效(但没有裁剪)。

\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}
4

1 回答 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}
于 2019-03-21T19:31:51.943 回答