1
votes

I have a folder with over 1000 pdf files. A small number of them cannot be opened (because the automatic download operation - performed in R with download.file in "wb" mode (win OS) somehow failed). I need to re-download them, but for this purpose I should get a list of them. How could I get it in an efficient manner?

I have used successfully a half-manual approach: using a for loop, I print the name of each file and use the pdf_info() on each file, which attempts to open it. For those affected by errors, I get a multiple error message like this:

PDF error: Couldn't find trailer dictionary

PDF error: Invalid XRef entry 6796

PDF error: Invalid XRef entry 408

PDF error: Invalid XRef entry 6770

PDF error: Top-level pages object is wrong type (null)

From 100 of files, in this way I identify 0-2 files affected by errors (because the file name is printed in front of the error). But then I have to re-download manually each file thus identified. I would like to use some condition, so that when I get such an error, the name of the file to be added to a vector of file names. I am just not able to understand how to use such a condition.

This is what I do now:

library(pdftools)

files <- list.files(pattern = "pdf$")

for (i in 1:100){
  print(i)
  pdf_info(files[i])
}

I would like to change the for loop (or to use alternative code), so as to be able to collect the names of the corrupted pdf files.

1

1 Answers

1
votes

Something like this should do it:

library(pdftools)

files <- list.files(pattern = "\\.pdf$")

for (file in files){
  corruptedPdfs <- list()

  tryPdfInfo <- tryCatch({
    pdf_info(file)
    }, error=function(e){e}
  )

  if(inherits(tryPdfInfo, "error")){
    corruptedPdfs[[file]] <- file
  }
}

print(corruptedPdfs)