daqana / tikzDevice

A R package for producing graphics output as PGF/TikZ code for use in TeX documents.
https://daqana.github.io/tikzDevice
131 stars 26 forks source link

Directly creating PDF files #211

Open jolars opened 3 years ago

jolars commented 3 years ago

I sometimes find myself wanting to produce PDF files directly, mostly to be able to automatically crop the resulting figures to avoid excessive margins.

I've created a utility function that looks like this:

tikzToPdf <- function(x) {
  wd <- getwd()
  on.exit({setwd(wd)})

  path <- normalizePath(dirname(x))

  full_file_path <- tools::file_path_as_absolute(x)
  file_wo_ext <- tools::file_path_sans_ext(basename(x))

  pdf_file <- paste0(file_wo_ext, ".pdf")

  # run latex in temporary directory
  tmp_dir <- tempdir()
  setwd(tmp_dir)

  # render tex file to pdf
  tools::texi2pdf(full_file_path)

  # move the file into the original directory
  success <- file.copy(pdf_file, file.path(path, pdf_file), overwrite = TRUE)

  invisible(success)
}

But it would obviously be much neater if this was possible directly through the tikz() interface. I'm not sure exactly how graphics devices work in R, but would it be possible to add some kind of hook to dev.off() to latexify the file into a pdf provided that the file ending in the call to tikz() is .pdf?