Skip to content

Instantly share code, notes, and snippets.

@ikashnitsky
Created December 21, 2023 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikashnitsky/c7037e2b1bc6d0d6e38fc4a41de9a8c7 to your computer and use it in GitHub Desktop.
Save ikashnitsky/c7037e2b1bc6d0d6e38fc4a41de9a8c7 to your computer and use it in GitHub Desktop.
R function to convert all PDFs in a directory into PNGs
#===============================================================================
# 2023-12-21 -- misc
# convert pdf to png
# Ilya Kashnitsky, ilya.kashnitsky@gmail.com, @ikashnitsky
#===============================================================================
#' @description A function to convert all PDFs in a directory into PNGs
#' @param dir_pdfs character. A character string with a path to the directory containing PDFs to convert
#' @param output_dir character. An optional parameter to specify the output directory for the converted PNGs. Defaults to `"/png"`, which creates a sub-directory `png` in the specified above `dir_pdfs` directory. Can be any location on the machine, one useful place may be something with all the temporary stuff like `"~/Downloads"`. Important: don't leave trailing slashes in the parameters.
convert_pdf_to_png <- function(dir_pdfs, output_dir = "/png") {
require(pdftools)
require(fs)
require(magrittr)
require(stringr)
require(purrr)
pdfs <- dir_ls(dir_pdfs) %>%
str_subset(".pdf")
base <- pdfs[1] %>%
str_remove("/[^/]+$")
if(output_dir == "/png"){
dir_create(path = paste0(base, "/png"))
convert_one_pdf <- function(path_to_pdf){
path = path_to_pdf %>% paste
pdf_convert(
pdf = path,
filenames = path %>%
str_remove(base) %>%
str_replace(".pdf", ".png") %>%
paste0(base, "/png", .),
dpi = 300
)
}
}else{
convert_one_pdf <- function(path_to_pdf){
path = path_to_pdf %>% paste
pdf_convert(
pdf = path,
filenames = path %>%
str_remove(base) %>%
str_replace(".pdf", ".png") %>%
paste0(output_dir %>% path_expand %>% paste, .),
dpi = 300
)
}
}
pdfs %>% map(convert_one_pdf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment