library(magrittr)
library(gt)
library(ggplot2)
library(htmltools)
# Define file numbers
file_nums <- sprintf("%03d", 2:2)
head(file_nums)
# 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$Material == "Phenolic Foam", ])),
      label = paste0("Phenolic Foam")
    ) %>%
    tab_row_group(
      rows = which(rownames(data) %in% rownames(data[data$Material == "Mineral Wool", ])),
      label = paste0("Mineral Wool")
#    rows_order(order = c("P00", "Group A"))
    ) %>%
    row_group_order(groups=c("Phenolic Foam","Mineral Wool")) %>%
    tab_header(title = gt::html("
Schedule of Pipework Insulation
")
  )  
table <- table %>%
  tab_style(
    style = list(
      cell_fill(color = "#FFCC00")
    ),
    locations = cells_row_groups()
  )
  # Save table as HTML
  html_file_name <- paste0("P", num, "_table.html")
#  header <- tags$h1(paste0("Report Title ", num))
#  html_content <- tagList(header, table)
#  html <- html_print(html_content)
#  write(html, file = paste0("P", num, "_table.html"))
  gtsave(table, file = html_file_name)
  # Convert HTML to PDF
#  pdf_file_name <- paste0("table", num, ".pdf")
#  system(paste0("wkhtmltopdf ", html_file_name, " ", pdf_file_name))
}
#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))
system("wkhtmltopdf -O landscape toc *.html output2.pdf")