Custom function to open compiled .rnw in Sumatra PDF reader?

Viewed 253

Since updating to Windows 10, I am unable to compile .rnw files with the "Compile PDF" button in Rstudio if they have citations (I use the natbib package). So, I have abandoned Sweave for Knitr. Though not as convenient as the Compile PDF button, the command

knitr::knit2pdf('my_doc.rnw')

compiles PDF's with R code, Latex, and citations without error. However, unlike the Compile PDF button, it does not automatically launch the newly-compiled PDF in Sumatra, my preferred PDF previewer. My question is, could the source code for knitr::knit2pdf, namely,

function (input, output = NULL, compiler = NULL, envir = parent.frame(), 
    quiet = FALSE, ...) 
{
    out = knit(input, output = output, envir = envir, quiet = quiet)
    owd = setwd(dirname(out))
    on.exit(setwd(owd))
    if (is.null(compiler)) {
        compiler = if (grepl("\\.rst$", out)) 
            "rst2pdf"
        else "pdflatex"
    }
    if (identical(compiler, "rst2pdf")) {
        if (tolower(file_ext(out)) != "rst") 
            stop("for rst2pdf compiler input must be a .rst file")
        rst2pdf(basename(out), ...)
    }
    else {
        tinytex::latexmk(basename(out), engine = compiler, ...)
    }
    with_ext(out, "pdf")
}

be amended to launch and update the newly-compile PDF each time I run knitr::knit2pdf? Thanks.

1 Answers

I would not recommend try to "amend" knit2pdf – but you can easily open your PDF in SumatraPDF after knitting. Just call:

system2("C:/Program Files/RStudio/bin/sumatra/SumatraPDF.exe", args = "my_doc.pdf", wait = FALSE, invisible = FALSE)

You may need to adjust the path to SumatraPDF.exe. SumatraPDF updates automatically when the PDF changes, so you don't need any extra effort to see changes.

If you prefer a oneliner for knitting and opening the PDF:

knit2sumatra <- function(input) {
  # "input" should be the filename WITHOUT extension
  knitr::knit2pdf(paste0(input, ".Rnw"))
  system2(
    "C:/Program Files/RStudio/bin/sumatra/SumatraPDF.exe",
    args = paste0(input, ".pdf"),
    wait = FALSE,
    invisible = FALSE
  )
}

Alternatively, just place the system2 call in a chunk (somewhere) in your RNW file. SumatraPDF will try to open the PDF too early – but as soon as compilation completes, the final PDF will be visible.

Related