I am building a pdf_book
book using bookdown, and successfully (on Mac and Windows).
But I want to do some post-processing on the tex file after it is produced, but before it is compiled by xelatex.
I had ideas for a method, but could not get things to work. (I asked here for help but got no replies… maybe because this new approach is the preferred way, if I could get it to work.)
But then I stumbled across adding a post_processor
option into my _output.yml
file; it seemed to be just was I was after!
But I cannot get it to work (neither Mac nor Windows). By this, I mean that the build goes OK from start to finish, but whatever I try to do in the post_processing
step just does not happen.
I’m not even sure where to find info about doing this; a web-search hasn’t shown much at all (I’ve been getting help from ChatGPT :->). So if anyone knows of where this is explained, that’d be great.
So I have this in my _output.yml
file:
bookdown::pdf_book:
latex_engine: xelatex
post_processor: !expr source('./post_processor.R')$post_processor
And the file post_processor.R
never seems to run; for example, even just print statements don’t appear; for the script below, for instance, the log
file is never created.
However, the same function does work OK if I run it from the R console:
post_processor(NULL, "./_book/_main.tex", "output.pdf", clean = TRUE, verbose = TRUE)
I know ChatGPT may be giving my dodgy info, but I can’t find much to guide me.
So: What must I do to get the post_processor.R
file to run when called in _output.yml
?
Any advice greatly appreciated.
P.
File post_processor.R
:
post_processor <- function(metadata, input_file, output_file, clean, verbose) {
log_file <- "post_processor_log.txt"
# Function to log messages by appending them to the log file
log_message <- function(message) {
log_conn <- file(log_file, open = "a") # Open the log file in append mode
writeLines(message, log_conn) # Write the message to the log
close(log_conn) # Close the connection
}
# Start logging
log_message("Log started and so it should haven")
# Check if the input .tex file exists
if (file.exists(input_file)) {
log_message(paste("Input file exists:", input_file, "n"))
# Read the .tex file
tex <- readLines(input_file)
# Write the modified .tex content back to the input file
writeLines(tex, input_file)
} else {
log_message("Input file does not exist!n")
}
# Final log message
log_message("Post-processing complete.n")
# Return the output file
return(output_file)
}