knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file()) # Set WD to Root
here::i_am("dev/alone.Rmd")
library(here)

Plan

2 Mains Wrapper:

usethis::use_r("thaipdf")

1. Thai PDF Document — Wrap rmarkdown::pdf_document()

New

Steps

  1. Render a temporary file from template-thai-preamble.tex with option

  2. thai_font

  3. line_spacing

use rmarkdown::pandoc_template()

  1. Run rmarkdown::pdf_document that includes temp thai-preamble and before_body
thaipdf_document <- function(thai_font = "TH Sarabun New", 
                             line_spacing = 1.5,
                             ...
                             ) {

  # Render a tmp file from template-thai-preamble.tex
  tmp_preamble <- tempfile("thai-preamble-", fileext = ".tex")
  # Write pandoc template to a location with variable substitution 
  tmp_preamble <- write_thai_preamble(path_abs = tmp_preamble, 
                                    thai_font = thai_font, 
                                    line_spacing = line_spacing)
  # Clean up when function exit
  ## See: https://stackoverflow.com/questions/28300713/how-and-when-should-i-use-on-exit
  on.exit(unlink(tmp_preamble), add = TRUE)

  rmarkdown::pdf_document(
    latex_engine = "xelatex",
    includes = rmarkdown::includes(
      in_header = tmp_preamble,
      before_body = before_body()
    ),
    ...
  )
}
tempfile("thai-preamble-", fileext = ".tex")
{print("hello"); Sys.sleep(2); print("World")}
j06 <- function(x) {
  cat("Hello\n")
  on.exit({Sys.sleep(1); cat("Goodbye!\n")}, add = TRUE)

  if (x) {
    return(10)
  } else {
    stop("Error")
  }
}

j06(10)

Old

thaipdf_document2 <- function(...) {
  rmarkdown::pdf_document(
    latex_engine = "xelatex",
    includes = rmarkdown::includes(
      in_header = thai_preamble(),
      before_body = before_body()
    ),
    ...
  )
}

Helper: Find path to Global Preamble & Before body

thai_preamble() = return path to global thai-preamble.tex

before_body() = return path to before_body which contains \sloppy

thai_preamble <- function(){
  thaipdf_paths()[["path_pre_global"]]
}

thai_preamble()
before_body <- function(){
  thaipdf_paths()[["path_before_body"]]
}

before_body()

2. THai PDF Book — Wrap bookdown::pdf_book()

thaipdf_book <- function(...) {

  # Check bookdown
  if (!requireNamespace("bookdown")) {
    cli::cli_alert_warning("This function require package {.pkg bookdown} installed.")
    cli::cli_li("To install run {.code install.packages('bookdown')}")
  }

  bookdown::pdf_book(
    base_format = thaipdf::thaipdf_document,
    ...
  )
}

Test if {bookdown} is not installed.

if(!requireNamespace("bookdown")){
  cli::cli_alert_warning("This function require package {.pkg bookdown} installed.")
  cli::cli_li("To install run {.code install.packages('bookdown')}")
}

HowTo

Howto: pdf_document and includes()

rmarkdown::includes()
rmarkdown::pdf_document()


Lightbridge-KS/thaipdf documentation built on June 18, 2022, 6:58 a.m.