library(magrittr) library(gt) library(ggplot2) library(htmltools) # Define file numbers file_nums <- sprintf("%03d", 1:10) # Create a temporary directory to store HTML files temp_dir <- tempdir() # Loop over the file numbers for (num in file_nums) { # Create file name file_name <- paste0("P", num, ".csv") # Read CSV file data <- read.csv(file_name) # Create table table <- gt(data) %>% tab_row_group( rows = which(rownames(data) %in% rownames(data[data$D1 == "C12", ])), label = paste0("P", num, "A") ) %>% tab_row_group( rows = which(rownames(data) %in% rownames(data[data$D1 == "C13", ])), label = paste0("P", num, "B") ) # Save table as HTML html_file_name <- paste0(temp_dir, "/P", num, "_table.html") # Create H1 header header <- tags$h1(paste0("Report Title ", num)) # Combine the header and table using htmltools html_content <- tagList(header, table) # Convert the combined content to HTML html <- html_print(html_content) # Save the HTML content to a file write(html, file = html_file_name) } # Get a list of all HTML files in the temporary directory html_files <- list.files(path = temp_dir, pattern = "\\.html$", full.names = TRUE) # Convert HTML files to PDF using wkhtmltopdf pdf_file_name <- "output.pdf" system2("wkhtmltopdf", c(html_files, pdf_file_name))