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